【问题标题】:Reading non-ASCII characters from a text file从文本文件中读取非 ASCII 字符
【发布时间】:2012-05-09 18:05:15
【问题描述】:

我正在使用 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。当我不从文件中读取时,任何字符都没有问题。

【问题讨论】:

  • 您期待什么结果?从技术上讲,python 已经正确读取了文件。
  • 为什么要逐个字符打印出来?为什么不直接说for line in f: print line?当我这样做时,它会根据需要打印“söcük”。
  • 我试过但没有用。它打印了 s\xc3\xb6zc\xc3\xbck.
  • Python 工作正常,问题是终端窗口/控制台中的编码。
  • 您确定您在 Windows 7“命令提示符”(黑屏)中打印并且您实际上看到 s\xc3\xb6zc\xc3\xbck 打印就像反斜杠 x c 3 等一样吗?真的确定你在做print line 而不是print repr(line)???

标签: python character-encoding


【解决方案1】:
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'))

【讨论】:

    【解决方案2】:
    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')
    

    【讨论】:

      【解决方案3】:

      这是终端编码。尝试使用您在文件中使用的相同编码配置您的终端。我建议你使用 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()
      

      【讨论】:

      • 现在我明白他们为什么在 3.0 中制定 UTF-8 标准了。 (PEP 3120)
      • @mgold:PEP 3120 是关于源 (.py) 文件的编码;这与 OP 的输入和/或输出编码问题无关。
      猜你喜欢
      • 1970-01-01
      • 2015-02-06
      • 2014-12-09
      • 1970-01-01
      • 1970-01-01
      • 2017-12-16
      • 2012-08-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多