0
# coding=UTF-8
with open('/home/marius/dev/python/navn/list.txt') as f:
    lines = f.read().splitlines()
    print lines

该文件/home/marius/dev/python/navn/list.txt包含带有一些特殊字符的字符串列表,例如æ,ø,å,Æ,Ø,Å。在终端中,这些都呈现为十六进制。我希望将它们呈现为 UTF-8。这是怎么做到的?

4

1 回答 1

4

通过将数据从 UTF-8 解码为 Unicode 值,然后让 Python 将这些值自动编码回终端编码:

with open('/home/marius/dev/python/navn/list.txt') as f:
    for line in f:
        print line.decode('utf8')

您可以io.open()在阅读时使用并为您解码数据:

import io

with io.open('/home/marius/dev/python/navn/list.txt', encoding='utf8') as f:
    for line in f:
        print line
于 2013-08-19T08:12:29.607 回答