【问题标题】:UTF-8 problem in python when reading chars读取字符时python中的UTF-8问题
【发布时间】:2009-06-12 07:39:00
【问题描述】:

我使用的是 Python 2.5。这里发生了什么?我误解了什么?我该如何解决?

in.txt:

Stäckövérfløw

code.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
print """Content-Type: text/plain; charset="UTF-8"\n"""
f = open('in.txt','r')
for line in f:
    print line
    for i in line:
        print i,
f.close()

输出:

Stäckövérfløw

S t � � c k � � v � � r f l � � w 

【问题讨论】:

    标签: python utf-8


    【解决方案1】:
    for i in line:
        print i,
    

    当你读取文件时,你读入的字符串是一个字节串。 for 循环一次迭代一个字节。这会导致 UTF-8 编码字符串出现问题,其中非 ASCII 字符由多个字节表示。如果您想使用 Unicode 对象,其中字符是基本部分,您应该使用

    import codecs
    f = codecs.open('in', 'r', 'utf8')
    

    如果sys.stdout 还没有合适的编码集,你可能需要包装它:

    sys.stdout = codecs.getwriter('utf8')(sys.stdout)
    

    【讨论】:

    • codecs.open中的'r'参数实际上是'rb'(没有'\n'转换)
    【解决方案2】:

    改用 codecs.open,它对我有用。

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    print """Content-Type: text/plain; charset="UTF-8"\n"""
    f = codecs.open('in','r','utf8')
    for line in f:
        print line
        for i in line:
            print i,
    f.close()
    

    【讨论】:

      【解决方案3】:

      看看这个:

      # -*- coding: utf-8 -*-
      import pprint
      f = open('unicode.txt','r')
      for line in f:
          print line
          pprint.pprint(line)
          for i in line:
              print i,
      f.close()
      

      它返回这个:

      Stäckövérfløw
      'St\xc3\xa4ck\xc3\xb6v\xc3\xa9rfl\xc3\xb8w'
      英石 ? ? ķķ? ? ? ? r f l ? ? w

      问题是文件只是被读取为一串字节。对它们进行迭代会将多字节字符拆分为无意义的字节值。

      【讨论】:

        【解决方案4】:
        print c,
        

        添加一个“空白字符”并将正确的 utf-8 序列分解为不正确的序列。因此,除非您将一个信号字节写入输出,否则这是行不通的

        sys.stdout.write(i)
        

        【讨论】:

          【解决方案5】:

          人们可能只想使用

          f = open('in.txt','r')
          for line in f:
              print line
              for i in line.decode('utf-8'):
                  print i,
          f.close()
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2010-12-25
            • 1970-01-01
            • 2017-02-04
            • 2017-04-26
            • 1970-01-01
            • 2014-09-07
            • 1970-01-01
            相关资源
            最近更新 更多