tugaa commited on
Commit
ff7e5fe
·
verified ·
1 Parent(s): 828cf43

Create mainapp.py

Browse files
Files changed (1) hide show
  1. mainapp.py +145 -0
mainapp.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## 依存ライブラリのインストール
2
+
3
+ ##このコードを実行するには、以下のライブラリが必要です。
4
+
5
+ ##```bash
6
+ ##pip install janome jaconv
7
+
8
+ import os
9
+ import re
10
+ from janome.tokenizer import Tokenizer
11
+ import jaconv
12
+
13
+ # 設定
14
+ input_folder = './aozora_texts'
15
+ output_folder = './comparison_output'
16
+
17
+ def extract_hiragana(text):
18
+ """
19
+ テキストデータから可能な限りひらがなを抽出します(漢字は読みをひらがなで)。
20
+ """
21
+ tokenizer = Tokenizer() # udic パラメータを削除
22
+ hiragana_words = []
23
+ for token in tokenizer.tokenize(text):
24
+ if token.reading != '*':
25
+ # 読みが存在する場合は、カタカナをひらがなに変換して追加
26
+ hiragana_words.append(jaconv.kata2hira(token.reading))
27
+ elif all('\u3041' <= char <= '\u3096' for char in token.surface):
28
+ # 読みがなく、表面形がひらがなの場合はそのまま追加
29
+ hiragana_words.append(token.surface)
30
+ elif token.part_of_speech.startswith('記号'):
31
+ # 記号はそのまま追加
32
+ hiragana_words.append(token.surface)
33
+ return "".join(hiragana_words)
34
+
35
+ def preprocess_text(text):
36
+ """
37
+ テキストデータの前処理を行います(行ごと処理)。
38
+ 改行コードの削除、空白の正規化、およびカタカナへの変換を行います。
39
+ """
40
+ text = text.replace('\r\n', '\n').replace('\r', '\n').strip()
41
+ text = re.sub(r'\s+', ' ', text)
42
+
43
+ tokenizer = Tokenizer() # udic パラメータを削除
44
+ katakana_words = []
45
+ for token in tokenizer.tokenize(text):
46
+ if token.reading == '*':
47
+ katakana_words.append(token.surface)
48
+ else:
49
+ katakana_words.append(token.reading)
50
+
51
+ return "".join(katakana_words)
52
+
53
+ def read_text_with_bom_removal(filepath, encoding='utf-8'):
54
+ """
55
+ BOM付きの可能性のあるテキストファイルを読み込み、BOMを取り除いて返します。
56
+ """
57
+ with open(filepath, 'rb') as f:
58
+ raw_data = f.read()
59
+
60
+ if raw_data.startswith(b'\xef\xbb\xbf'):
61
+ return raw_data[3:].decode(encoding)
62
+ else:
63
+ return raw_data.decode(encoding)
64
+
65
+ def output_comparison_data(filename, original_text, preprocessed_text, hiragana_text, output_folder):
66
+ """
67
+ 元のテキスト、カタカナ変換後のテキスト、ひらがな抽出後のテキストを行ごとにタブ区切りでファイルに出力します。
68
+ 出力フォルダを引数として受け取ります。
69
+ """
70
+ if not os.path.exists(output_folder):
71
+ os.makedirs(output_folder)
72
+
73
+ base_filename, ext = os.path.splitext(filename)
74
+ output_filepath = os.path.join(output_folder, f"{base_filename}_comparison.tsv")
75
+
76
+ try:
77
+ with open(output_filepath, 'w', encoding='utf-8', errors='ignore') as outfile:
78
+ outfile.write("Original\tKatakana\tHiragana\n")
79
+ original_lines = original_text.splitlines()
80
+ preprocessed_lines = preprocessed_text.splitlines()
81
+ hiragana_lines = hiragana_text.splitlines()
82
+
83
+ max_lines = max(len(original_lines), len(preprocessed_lines), len(hiragana_lines))
84
+ for i in range(max_lines):
85
+ original = original_lines[i] if i < len(original_lines) else ""
86
+ preprocessed = preprocessed_lines[i] if i < len(preprocessed_lines) else ""
87
+ hiragana = hiragana_lines[i] if i < len(hiragana_lines) else ""
88
+ outfile.write(f"{original}\t{preprocessed}\t{hiragana}\n")
89
+
90
+ print(f"比較データを '{output_filepath}' に出力しました。")
91
+
92
+ except Exception as e:
93
+ print(f"エラー: ファイル '{output_filepath}' への書き込みに失敗しました: {e}")
94
+
95
+ def process_file(filename, input_folder, output_folder):
96
+ """
97
+ 指定されたファイル名で、input_folder内のテキストファイルを読み込み、
98
+ 行ごとに前処理(カタカナ変換)とひらがな抽出を行い、比較データを出力します。
99
+ """
100
+ filepath = os.path.join(input_folder, filename)
101
+ try:
102
+ original_text = read_text_with_bom_removal(filepath)
103
+ original_lines = original_text.splitlines()
104
+ preprocessed_lines = []
105
+ hiragana_lines = []
106
+
107
+ for line in original_lines:
108
+ if line.strip():
109
+ preprocessed_line = preprocess_text(line)
110
+ hiragana_line = extract_hiragana(line)
111
+ preprocessed_lines.append(preprocessed_line)
112
+ hiragana_lines.append(hiragana_line)
113
+ else:
114
+ preprocessed_lines.append("") # 空行を保持
115
+ hiragana_lines.append("") # 空行を保持
116
+
117
+ output_comparison_data(filename, original_text, "\n".join(preprocessed_lines), "\n".join(hiragana_lines), output_folder)
118
+
119
+ except FileNotFoundError:
120
+ print(f"エラー: ファイル '{filepath}' が見つかりません。")
121
+ except Exception as e:
122
+ print(f"エラー: ファイル '{filepath}' の処理中にエラーが発生しました: {e}")
123
+
124
+ def load_text_files(folder_path):
125
+ """
126
+ 指定されたフォルダ内の .txt ファイルのリストを返します。
127
+ """
128
+ text_files = [f for f in os.listdir(folder_path) if f.endswith('.txt')]
129
+ return text_files
130
+
131
+ if __name__ == "__main__":
132
+ try:
133
+ import jaconv
134
+ except ImportError:
135
+ print("エラー: 'jaconv' ライブラリがインストールされていません。インストールするには 'pip install jaconv' を実行してください。")
136
+ exit()
137
+
138
+ text_files = load_text_files(input_folder)
139
+ if not text_files:
140
+ print(f"フォルダ '{input_folder}' にテキストファイルが見つかりませんでした。")
141
+ else:
142
+ for filename in text_files:
143
+ print(f"処理中のファイル: {filename}")
144
+ process_file(filename, input_folder, output_folder)
145
+ print("すべてのファイルの処理が完了しました。")