100 個のファイルがあり、chardet によると、各ファイルは次のいずれかでエンコードされています。
['UTF-8', 'ascii', 'ISO-8859-2', 'UTF-16LE', 'TIS-620', 'utf-8', 'SHIFT_JIS', 'ISO-8859-7']
ファイルのエンコーディングを知っているので、どのエンコーディングでファイルを開くかを知っています。
すべてのファイルを ascii のみに変換したい。-
また、 や などのさまざまなバージョンの文字'
をプレーンな ASCIIに変換したいと考えています。たとえば、b"\xe2\x80\x94".decode("utf8")
に変換する必要があります-
。最も重要なことは、テキストが読みやすいことです。don t
私は例を望んでいませんが、don't
代わりに。
どうすればこれを行うことができますか?
これを解決するには、Python 2 または 3 を使用できます。
これは私が Python2 で得た限りです。そもそもASCII以外の文字が続く行を検出しようとしています。
for file_name in os.listdir('.'):
print(file_name)
r = chardet.detect(open(file_name).read())
charenc = r['encoding']
with open(file_name,"r" ) as f:
for line in f.readlines():
if line.decode(charenc) != line.decode("ascii","ignore"):
print(line.decode("ascii","ignore"))
これにより、次の例外が発生します。
if line.decode(charenc) != line.decode("ascii","ignore"):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/utf_16_le.py", line 16, in decode
return codecs.utf_16_le_decode(input, errors, True)
UnicodeDecodeError: 'utf16' codec can't decode byte 0x0a in position 6: truncated data