ファイルからの読み込み、文字列の処理、UTF-8ファイルへの保存に問題があります。
以下はそのコードです。
try:
filehandle = open(filename,"r")
except:
print("Could not open file " + filename)
quit()
text = filehandle.read()
filehandle.close()
次に、変数textに対して何らかの処理を行います。
そしてその後
try:
writer = open(output,"w")
except:
print("Could not open file " + output)
quit()
#data = text.decode("iso 8859-15")
#writer.write(data.encode("UTF-8"))
writer.write(text)
writer.close()
これでファイルは完璧に出力されますが、私のエディタによるとiso 8859-15で出力されます。同じエディタでは入力ファイル(変数filenameで)をUTF-8として認識しているので、なぜこのようなことが起こったのかわかりません。私が調べた限りでは、コメントされた行が問題を解決するはずです。しかし、私がこれらの行を使用すると、結果として得られるファイルは、主に特殊文字、チルダを含む単語、テキストがスペイン語であるため、不可解なものになります。困っているので、助けていただけると助かります。....
codecs`モジュールを使って、プログラムのI/O境界でUnicodeとの間でテキストを処理することができます。
import codecs
with codecs.open(filename, 'r', encoding='utf8') as f:
text = f.read()
# process Unicode text
with codecs.open(filename, 'w', encoding='utf8') as f:
f.write(text)
編集: codecsの代わりに io
モジュールが推奨され、Python 3'の open
構文と互換性があります。
import io
with io.open(filename, 'r', encoding='utf8') as f:
text = f.read()
# process Unicode text
with io.open(filename, 'w', encoding='utf8') as f:
f.write(text)
また、下記のコードでもご利用いただけますので、ぜひご利用ください。
file=open(completefilepath,'r',encoding='utf8',errors="ignore")
file.read()