我正在使用Python 2.7。我尝试过许多方法,如codecs,但都没有起作用。我该怎么解决这个问题。
myfile.txt
wörd
我的代码
f = open('myfile.txt','r')
for line in f:
print line
f.close()
输出
s\xc3\xb6zc\xc3\xbck
在Eclipse和命令窗口上输出相同。我使用的是Win7。当我不从文件中读取时,任何字符都没有问题。
我正在使用Python 2.7。我尝试过许多方法,如codecs,但都没有起作用。我该怎么解决这个问题。
myfile.txt
wörd
我的代码
f = open('myfile.txt','r')
for line in f:
print line
f.close()
输出
s\xc3\xb6zc\xc3\xbck
在Eclipse和命令窗口上输出相同。我使用的是Win7。当我不从文件中读取时,任何字符都没有问题。
import codecs
#open it with utf-8 encoding
f=codecs.open("myfile.txt","r",encoding='utf-8')
#read the file to unicode string
sfile=f.read()
#check the encoding type
print type(file) #it's unicode
#unicode should be encoded to standard string to display it properly
print sfile.encode('utf-8')
#check the type of encoded string
print type(sfile.encode('utf-8'))
from chardet import detect
encoding = lambda x: detect(x)['encoding']
print encoding(line)
n_line=unicode(line,encoding(line),errors='ignore')
print n_line
print n_line.encode('utf8')
这是终端编码的问题。尝试使用与文件相同的编码配置您的终端。我建议您使用UTF-8。
顺便说一句,为了避免问题,将所有输入输出进行解码和编码是一个好习惯:
f = open('test.txt','r')
for line in f:
l = unicode(line, encoding='utf-8')# decode the input
print l.encode('utf-8') # encode the output
f.close()
for line in f: print line
呢?当我这样做时,它按预期打印了 "söcük"。 - srgergs\xc3\xb6zc\xc3\xbck
就像那样打印,包括反斜杠x c 3等吗??你真的确定你正在执行print line
而不是print repr(line)
吗?? - John Machin