| import os | |
| import pandas as pd | |
| BASE_DIR = os.path.join(".") | |
| if __name__ == "__main__": | |
| chapters = [] | |
| for root, dirs, files in os.walk(os.path.join(BASE_DIR, "documents")): | |
| if "extracted_text.md" in files: | |
| with open(os.path.join(root, "extracted_text.md"), "r", encoding="utf-8") as file: | |
| full_path = os.path.join(root, "extracted_text.md") | |
| text = file.read() | |
| lines = text.split("\n") | |
| chapters_indices = [i for i in range(len(lines)) if lines[i].startswith("# ")] | |
| for i in range(len(chapters_indices)): | |
| next_index = chapters_indices[i + 1] if i < len(chapters_indices) - 1 else len(lines) | |
| title = lines[chapters_indices[i]][2:].strip() | |
| content = '\n'.join(lines[chapters_indices[i] + 1:next_index]) | |
| content = '\n'.join(line.rstrip() for line in content.split("\n")) | |
| content = content.rstrip() | |
| chapters.append({ | |
| 'region': full_path.split('\\')[-5], | |
| 'topic': full_path.split('\\')[-4], | |
| 'document_type': full_path.split('\\')[-3], | |
| 'entity': full_path.split('\\')[-2].split('_')[1], | |
| 'document_date': full_path.split('\\')[-2].split('_')[0], | |
| 'document_id': full_path.split('\\')[-2].split('_')[2], | |
| 'progress': i+1, | |
| "title": title, | |
| "content": content | |
| }) | |
| df = pd.DataFrame(chapters).sort_values(by=['region', 'topic', 'document_type', 'document_id', 'progress']) | |
| df.to_csv(os.path.join(BASE_DIR, 'corpus.csv'), index=False, encoding='utf-8') | |
| df.to_csv(os.path.join(BASE_DIR, 'corpus.tsv'), sep='\t', index=False, encoding='utf-8') | |
| df.to_excel(os.path.join(BASE_DIR, 'corpus.xlsx'), index=False) | |