读取字符时python中的UTF-8问题

时间:2009-06-12 07:39:00

标签: python utf-8

我正在使用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 

5 个答案:

答案 0 :(得分:14)

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)

答案 1 :(得分: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()

答案 2 :(得分:1)

检查出来:

# -*- 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()

它返回:

计算器
'圣\ XC3 \ xa4ck \ XC3 \ xb6v \ XC3 \ xa9rfl \ XC3 \ xb8w'
S? ? c k? ? v? ? r f l? ? w

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

答案 3 :(得分:1)

print c,

添加“空白charrecter”并将正确的utf-8序列分解为错误的序列。所以除非你写一个signle字节输出

,否则这不会起作用
sys.stdout.write(i)

答案 4 :(得分:0)

有人可能只想使用

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