【问题标题】:How to read Unicode file as Unicode string in Python [closed]如何在 Python 中将 Unicode 文件读取为 Unicode 字符串 [关闭]
【发布时间】:2023-03-20 14:50:02
【问题描述】:

我有一个以 Unicode 或 UTF-8 编码的文件(我不知道是哪个)。当我在 Python 3.4 中读取文件时,结果字符串被解释为 ASCII 字符串。如何将其转换为像 u"text" 这样的 Unicode 字符串?

【问题讨论】:

    标签: python python-3.x unicode character-encoding ascii


    【解决方案1】:

    术语“Unicode”指的是标准,而不是特定的编码。 由于计算机中的文件是二进制文件,因此存在将 Unicode 数据编码到二进制文件中的不同方法。其中之一是“UTF-8”。

    您可以咨询https://docs.python.org/3/howto/unicode.html

    取自本文档的示例(在“读取和写入 Unicode 数据”部分)

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

    在 python 3 中,与 python2 不同的是,unicode 字符串常量不写有“u”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多