5

我正在使用python 2.7。我已经尝试了很多东西,比如编解码器,但没有奏效。我怎样才能解决这个问题。

我的文件.txt

wörd

我的代码

f = open('myfile.txt','r')
for line in f:
    print line
f.close()

输出

s\xc3\xb6zc\xc3\xbck

Eclipse 和命令窗口的输出相同。我用的是Win7。当我不从文件中读取时,任何字符都没有问题。

4

3 回答 3

15
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'))
于 2013-02-09T11:58:32.903 回答
7
  1. 首先 - 检测文件的编码

  from chardet import detect
  encoding = lambda x: detect(x)['encoding']
  print encoding(line)
  1. 然后 - 将其转换为 unicode 或您的默认编码 str:

  n_line=unicode(line,encoding(line),errors='ignore')
  print n_line
  print n_line.encode('utf8')
于 2012-04-30T00:16:51.200 回答
1

这是终端编码。尝试使用您在文件中使用的相同编码配置您的终端。我建议您使用 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()
于 2012-04-30T00:18:12.270 回答