在Python中从文件读取字符

122 投票
9 回答
309226 浏览
提问于 2025-04-11 09:23

在一个文本文件里,有一句话是“I don't like this”。

但是,当我把它读进一个字符串的时候,它变成了“I don\xe2\x80\x98t like this”。我知道,\u2018是“'”这个符号的unicode表示。为了读取这个字符串,我使用了

f1 = open (file1, "r")
text = f1.read()

这个命令。

现在,有没有办法让它在读取的时候直接变成“I don't like this”,而不是“I don\xe2\x80\x98t like this”呢?

第二次编辑:我看到有些人用映射来解决这个问题,但真的没有什么内置的方法可以直接把ANSI转换成unicode(反之亦然)吗?

9 个回答

15

有几个要点需要注意。

在Python中,‘\u2018’这个字符可能只是一个unicode字符串的一部分,比如如果你写:

>>> text = u'‘'
>>> print repr(text)
u'\u2018'

如果你只是想把这个unicode字符串好看地打印出来,可以直接使用unicode的encode方法:

>>> text = u'I don\u2018t like this'
>>> print text.encode('utf-8')
I don‘t like this

为了确保从任何文件读取的每一行都是unicode格式,最好使用codecs.open函数,而不是简单的open,这样你可以指定文件的编码方式:

>>> import codecs
>>> f1 = codecs.open(file1, "r", "utf-8")
>>> text = f1.read()
>>> print type(text)
<type 'unicode'>
>>> print text.encode('utf-8')
I don‘t like this
27

你也可以用Python 3的读取方法来读取一个编码过的文本文件:

f = open (file.txt, 'r', encoding='utf-8')
text = f.read()
f.close()

用这种方式,你不需要导入任何额外的库。

196

参考链接: http://docs.python.org/howto/unicode

从文件中读取Unicode(统一码)非常简单:

import codecs
with codecs.open('unicode.rst', encoding='utf-8') as f:
    for line in f:
        print repr(line)

你也可以以更新模式打开文件,这样就可以同时进行读取和写入:

with codecs.open('test', encoding='utf-8', mode='w+') as f:
    f.write(u'\u4500 blah blah blah\n')
    f.seek(0)
    print repr(f.readline()[:1])

编辑: 我假设你想要的目标只是能够正确地将文件内容读入Python中的字符串。如果你想把Unicode转换成ASCII字符串,那其实没有直接的方法,因为Unicode字符不一定在ASCII中都有对应的字符。

如果你想转换成ASCII字符串,可以尝试以下几种方法:

  1. 如果你只想处理一些特定的情况,比如这个例子,可以把特定的Unicode字符替换成ASCII字符。

  2. 使用unicodedata模块的normalize()方法和string.encode()方法,尽量将Unicode字符转换成最接近的ASCII字符(参考链接 https://web.archive.org/web/20090228203858/http://techxplorer.com/2006/07/18/converting-unicode-to-ascii-using-python):

    >>> teststr
    u'I don\xe2\x80\x98t like this'
    >>> unicodedata.normalize('NFKD', teststr).encode('ascii', 'ignore')
    'I donat like this'
    

撰写回答