| |
| """ |
| Script to add jyutping column to all metadata.csv files in the dataset. |
| Includes custom entries for specific terms. |
| """ |
|
|
| import csv |
| import os |
| import ToJyutping |
| from pathlib import Path |
|
|
| def add_jyutping_to_csv(csv_path, converter): |
| """Add jyutping column to a CSV file using the provided converter.""" |
| print(f"Processing {csv_path}...") |
| |
| |
| rows = [] |
| with open(csv_path, 'r', encoding='utf-8') as f: |
| reader = csv.DictReader(f) |
| fieldnames = reader.fieldnames |
| |
| |
| if 'jyutping' not in fieldnames: |
| fieldnames = fieldnames + ['jyutping'] |
| |
| |
| for i, row in enumerate(reader): |
| |
| transcription = row['transcription'] |
| jyutping = converter.get_jyutping_text(transcription) |
| row['jyutping'] = jyutping |
| rows.append(row) |
| |
| |
| if (i + 1) % 1000 == 0: |
| print(f" Processed {i + 1} rows...") |
| |
| |
| output_path = csv_path.with_suffix('.tmp') |
| with open(output_path, 'w', encoding='utf-8', newline='') as f: |
| writer = csv.DictWriter(f, fieldnames=fieldnames) |
| writer.writeheader() |
| writer.writerows(rows) |
| |
| |
| output_path.replace(csv_path) |
| print(f" Completed! Total rows processed: {len(rows)}") |
|
|
| def main(): |
| """Main function to process all metadata.csv files.""" |
| |
| |
| |
| custom_entries = { |
| '刻': 'hak1', |
| } |
| |
| |
| converter = ToJyutping.customize(custom_entries) |
| |
| |
| csv_files = [ |
| Path("/Users/laufei/Documents/GitHub/zoengjyutgaai_saamgwokjinji/opus/seoiwuzyun/metadata.csv"), |
| Path("/Users/laufei/Documents/GitHub/zoengjyutgaai_saamgwokjinji/opus/saamgwokjinji/metadata.csv"), |
| Path("/Users/laufei/Documents/GitHub/zoengjyutgaai_saamgwokjinji/opus/mouzaakdung/metadata.csv"), |
| Path("/Users/laufei/Documents/GitHub/zoengjyutgaai_saamgwokjinji/opus/lukdinggei/metadata.csv") |
| ] |
| |
| print("Using custom entries:") |
| for term, jyutping in custom_entries.items(): |
| print(f" {term} -> {jyutping}") |
| print() |
| |
| |
| for csv_file in csv_files: |
| if csv_file.exists(): |
| add_jyutping_to_csv(csv_file, converter) |
| else: |
| print(f"Warning: {csv_file} not found!") |
| |
| print("\nAll files processed successfully!") |
|
|
| if __name__ == "__main__": |
| main() |
|
|