gpt4 book ai didi

python - 在 Python 中从文件中读取字符

转载 作者:IT老高 更新时间:2023-10-28 21:09:13 26 4
gpt4 key购买 nike

在一个文本文件中,有一个字符串“我不喜欢这个”。

但是,当我将它读入字符串时,它变成了“我不喜欢这样\xe2\x80\x98t”。我知道\u2018 是“'”的 unicode 表示。我用

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

执行读取的命令。

现在,是否有可能以这样的方式读取字符串,当它被读入字符串时,它是“我不喜欢这个”,而不是“我不喜欢这样\xe2\x80\x98t这个”?

第二次编辑:我看到有人使用映射来解决这个问题,但实际上,没有内置的转换可以将这种 ANSI 转换为 unicode(反之亦然)吗?

最佳答案

引用: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. 如果您只想处理一些特殊情况,例如这个特定示例,请用 ASCII 等价物替换特定的 unicode 字符

  2. 使用 unicodedata 模块的 normalize()string.encode() 方法尽可能地转换为下一个最接近的 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'

关于python - 在 Python 中从文件中读取字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/147741/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com