python 来自 genfromtxt 的 3 个日文字母

python 3 japanese letters from genfromtxt

我正在开发一个程序,该程序使用 .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 中则不行。那么,是否可以将这些字符解码为python3?

test.txt 是如何编码的?我怀疑它是使用 utf-8 编码的。如果是这样,请在 Python3:

中尝试此操作
test=open("test.txt", "r", encoding="utf-8")