【发布时间】:2018-04-02 19:58:08
【问题描述】:
我正在开发一个程序,该程序使用 .txt 文件中的数据并处理所述数据。数据主要包含拉丁字符,但有时也有 日语字符。这就是我想做的:
# -- coding: UTF-8 --
import numpy as np
test=open("test.txt", "r")
test2=open("list.txt", "w")
test2.write("# ")
for line in test:
line2=line.replace('""', "(None)")
line3=line2.replace('"', "")
line4=line3.replace(" ", "_")
line5=line4.replace(",", " ")
test2.write(line5)
它可以正常工作,但有一些日文字符会导致问题。有趣的是,像ゲ、ノ、セ、ト或ク这样的字符没什么大不了的,但这些字符是:いがか。
一旦其中一个隐藏在 test.txt 中的某个位置,就会出现以下错误消息:
UnicodeDecodeError Traceback (most recent call last) C:\Users\syhon\Documents\DV-Liste\ListeV2.0\ListeV2.py in <module>()
196
197 test2.write("# ")
--> 198 for line in test:
199 line2=line.replace('""', "(None)")
200 line3=line2.replace('"', "")
C:\Users\syhon\Anaconda3\lib\encodings\cp1252.py in decode(self, input, final)
21 class IncrementalDecoder(codecs.IncrementalDecoder):
22 def decode(self, input, final=False):
---> 23 return codecs.charmap_decode(input,self.errors,decoding_table)[0]
24
25 class StreamWriter(Codec,codecs.StreamWriter):
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 6281: character maps to <undefined>
但是,我发现我可以在 python 2 中毫无问题地打印所述字符,但在 python 3 中却不行。那么,是否可以在 python 3 中解码这些字符?
【问题讨论】:
标签: python genfromtxt cjk