Create scripts/03a_analyze_lexicon_frequency.py
Browse files
scripts/03a_analyze_lexicon_frequency.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
from collections import Counter
|
| 3 |
+
import os
|
| 4 |
+
import json
|
| 5 |
+
from tqdm import tqdm
|
| 6 |
+
|
| 7 |
+
# ----------------------------------------
|
| 8 |
+
# 1. 설정
|
| 9 |
+
# ----------------------------------------
|
| 10 |
+
# 전처리된 데이터 파일 경로 (이 스크립트는 모델이 아닌 전처리 데이터가 필요합니다)
|
| 11 |
+
# Colab 등 다른 환경에서 실행 시, 이 파일을 Hugging Face Hub (비공개)에서 다운로드해야 합니다.
|
| 12 |
+
input_file_path = '/chosun_pos_tagged_parallel.jsonl'
|
| 13 |
+
# 출력 파일 경로
|
| 14 |
+
output_dir = '/koselleck_analysis_results'
|
| 15 |
+
output_file_path = os.path.join(output_dir, 'lexicon_frequency.csv')
|
| 16 |
+
|
| 17 |
+
# ----------------------------------------
|
| 18 |
+
# 2. 어휘 목록(Lexicon) 정의
|
| 19 |
+
# ----------------------------------------
|
| 20 |
+
print("1. 분석에 사용할 어휘 목록을 정의합니다.")
|
| 21 |
+
experience_lexicon = [
|
| 22 |
+
'과거', '역사', '어제', '작년', '옛날', '예전', '고대', '중세', '근세', '왕조', '시대', '지난', '선대', '전대', '구세대', '당대', '기왕',
|
| 23 |
+
'기억', '추억', '회고', '기록', '실록', '연대기', '문헌', '사료', '증언', '구술', '족보', '회상', '반성', '성찰', '교훈', '기념', '추모', '고증',
|
| 24 |
+
'전통', '유산', '유물', '유적', '관습', '관행', '선례', '전례', '계승', '답습', '풍속', '의례', '제사', '관혼상제', '고사',
|
| 25 |
+
'기원', '뿌리', '근본', '연원', '내력', '배경', '발자취', '흔적', '자취', '혈통', '가문', '유래',
|
| 26 |
+
'선조', '조상', '선인', '선현', '위인', '후손', '사대부', '양반',
|
| 27 |
+
'재현', '복원', '재평가', '재조명', '복고', '향수', '회귀', '역사교육', '국사', '동양사', '서양사', '세계사'
|
| 28 |
+
]
|
| 29 |
+
expectation_lexicon = [
|
| 30 |
+
'미래', '장래', '내일', '내년', '다음', '후일', '후대', '후세', '차세대', '신세대', '장차',
|
| 31 |
+
'희망', '기대', '전망', '예측', '예언', '이상', '꿈', '소망', '염원', '비전', '가능성', '잠재력', '기회',
|
| 32 |
+
'계획', '설계', '목표', '청사진', '공약', '정책', '약속', '전략', '구상', '준비', '대비',
|
| 33 |
+
'발전', '성장', '진보', '개발', '건설', '부흥', '도약', '혁신', '창조', '개혁', '개선', '변화', '변혁', '혁명', '번영',
|
| 34 |
+
'신세계', '신시대', '신기술', '신제품', '창업', '건국', '개척', '선도', '주도', '모색', '탐구', '신설', '창간',
|
| 35 |
+
'청년', '어린이', '학생', '교육', '인재', '양성'
|
| 36 |
+
]
|
| 37 |
+
experience_set = set(experience_lexicon)
|
| 38 |
+
expectation_set = set(expectation_lexicon)
|
| 39 |
+
|
| 40 |
+
# ----------------------------------------
|
| 41 |
+
# 3. 전처리된 데이터 로드 및 분석
|
| 42 |
+
# ----------------------------------------
|
| 43 |
+
print("\n2. 전처리된 데이터 로드 및 분석을 시작합니다.")
|
| 44 |
+
try:
|
| 45 |
+
data = []
|
| 46 |
+
with open(input_file_path, 'r', encoding='utf-8') as f:
|
| 47 |
+
for line in tqdm(f, desc="파일 로딩"):
|
| 48 |
+
data.append(json.loads(line))
|
| 49 |
+
df = pd.DataFrame(data)
|
| 50 |
+
df = df[df['type'] == 'article'].copy()
|
| 51 |
+
print("파일 로드 완료.")
|
| 52 |
+
|
| 53 |
+
print("\n연도별 어휘 빈도를 계산합니다...")
|
| 54 |
+
yearly_counts = {}
|
| 55 |
+
for index, row in tqdm(df.iterrows(), total=df.shape[0], desc="빈도 계산"):
|
| 56 |
+
year = row['year']
|
| 57 |
+
if year not in yearly_counts:
|
| 58 |
+
yearly_counts[year] = {'total_nouns': 0, 'exp_count': 0, 'expc_count': 0}
|
| 59 |
+
|
| 60 |
+
nouns = [word for word, pos in row['pos_tagged_body'] if pos == 'Noun']
|
| 61 |
+
yearly_counts[year]['total_nouns'] += len(nouns)
|
| 62 |
+
yearly_counts[year]['exp_count'] += sum(1 for noun in nouns if noun in experience_set)
|
| 63 |
+
yearly_counts[year]['expc_count'] += sum(1 for noun in nouns if noun in expectation_set)
|
| 64 |
+
|
| 65 |
+
yearly_data = []
|
| 66 |
+
for year, counts in sorted(yearly_counts.items()):
|
| 67 |
+
total_nouns = counts['total_nouns']
|
| 68 |
+
if total_nouns > 0:
|
| 69 |
+
exp_freq = (counts['exp_count'] / total_nouns) * 10000
|
| 70 |
+
expc_freq = (counts['expc_count'] / total_nouns) * 10000
|
| 71 |
+
yearly_data.append({'year': year, 'experience_freq': exp_freq, 'expectation_freq': expc_freq})
|
| 72 |
+
|
| 73 |
+
freq_df = pd.DataFrame(yearly_data)
|
| 74 |
+
print("\n[연도별 어휘 빈도 계산 결과 (상위 5개)]")
|
| 75 |
+
print(freq_df.head())
|
| 76 |
+
|
| 77 |
+
print("\n분석 결과를 파일로 저장합니다.")
|
| 78 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 79 |
+
freq_df.to_csv(output_file_path, index=False, encoding='utf-8-sig')
|
| 80 |
+
print(f"시계열 빈도 분석 결과가 다음 경로에 저장되었습니다: {output_file_path}")
|
| 81 |
+
|
| 82 |
+
except FileNotFoundError:
|
| 83 |
+
print(f"오류: '{input_file_path}'를 찾을 수 없습니다.")
|
| 84 |
+
except Exception as e:
|
| 85 |
+
print(f"알 수 없는 오류가 발생했습니다: {e}")
|