eigo.txt
1,364 2of,44 3the,34 4in,25 5was,21 60,18 7at,17 8and,16 9g,15 10for,13 115,13 12a,12 13ph,12 14with,11 15to,10 16were,10 17pga,9 181,9 19ao,9 20natto,8 21b,8 22by,8 23buffer,8
このtxtの、「,数字」が邪魔なのですが、色々と方法があるのですが、
「,」より左側だけを読み取っていく方針だと、どうなるでしょうか。
全部読み取ろうとすると、以下のようになり、
python
1def main(): 2 with open(WORDS_FILE_PATH, mode="r", encoding="utf-8") as f: 3 words = f.readlines() 4 5 example = sentence() 6 out_text = "" 7 for word in words: 8 try: 9 result = example.get_sentence_list(word, 1)[0] 10 except RuntimeError as e: 11 result = e 12 out_text += f"{word.rstrip()}, {result}\n" 13 14 with open(OUT_FILE_PATH, mode="w", encoding="utf-8") as f: 15 f.write(out_text)
こんなエラーになります。
Traceback (most recent call last): File "C:\Users\a\Desktop\yomitori.py", line 53, in <module> main() File "C:\Users\a\Desktop\yomitori.py", line 37, in main words = f.readlines() File "C:\Users\a\AppData\Local\Programs\Python\Python39\lib\codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0x81 in position 199: invalid start byte
yomitori.pyは上のコードを書いたファイルです、これはたぶん「,」を含んでるものを読み取った結果のエラーだと思うのですが、では「,」の左側までを、各行読み取っていくにはどのようにすれば良いのでしょうか・・・。
色々調べて、
python
1# 01 文章を単語に分ける 2# 複数の区切り文字を指定するため re.split を使う 3words = re.split(r'\s|\,|\.|\(|\)', target_text.lower()) 4 5# 02 集計する 6counter = Counter(words) 7 8# 02.5 要素・出現回数のリスト個別に取得 9values, counts = zip(*counter.most_common()) 10 11# 02.6 csv出力 12with open("eigo.csv", "a", newline="") as f: 13 writer = csv.writer(f) 14 writer.writerows(values)
こうすることにしました、まず初めの説明。そもそもcounter.most_commonは文字と頻出数の2つのリストに分けて取得ができるようで、こうして文字の方であるvaluesのみを取る事にしました。
output(values)
1('', 'of', 'the', 'in', 'was', '0', 'at', 'and', 'g', 'for', '5', 'a', 'ph', 'with', 'to', 'were', 'pga', '1', 'ao', 'natto', 'b', 'by', 'buffer'・・・)
そのvaluesをcsvに書き込もうとしました、文字コードのエラーが生じないように。実際に生じませんでしたが、できたファイルは・・・
eigo.csv
1,364 2of,44 3the,34 4in,25 5was,21 60,18 7・・・
このように、変わってません、なぜか「,」と「数字」が相変わらず入ってます。valueには英語のみのはずなのになぜ??