【问题标题】:How to decode unicode string that is read from a file in Python?如何解码从 Python 文件中读取的 unicode 字符串?
【发布时间】:2020-12-06 12:49:43
【问题描述】:

我有一个包含 UTF-16 字符串的文件。当我尝试读取 unicode 时,会添加“”(双引号)并且字符串看起来像 "b'\\xff\\xfeA\\x00'"。内置的.decode 函数会抛出AttributeError: 'str' object has no attribute 'decode'。我尝试了几个选项,但都不起作用。

This is what the file I am reading from looks like

【问题讨论】:

  • 你能把你尝试过的包括进来吗?这将使您更容易确定您需要帮助的地方。
  • 我已经尝试.decode('unicode_escape') 并再次编码然后解码(这会打印一些中文字符)。

标签: python python-3.x character-encoding utf-16 python-unicode


【解决方案1】:

试试这个:

str.encode().decode()

【讨论】:

    【解决方案2】:

    看起来文件是通过向其写入字节文字来创建的,如下所示:

    some_bytes = b'Hello world'
    with open('myfile.txt', 'w') as f:
        f.write(str(some_bytes))
    

    这解决了尝试将字节写入以文本模式打开的文件会引发错误的事实,但代价是文件现在包含"b'hello world'"(请注意引号内的“b”)。

    解决方法是在写入之前将bytes解码为str

    some_bytes = b'Hello world'
    my_str = some_bytes.decode('utf-16') # or whatever the encoding of the bytes might be
    with open('myfile.txt', 'w') as f:
        f.write(my_str)
    

    或以二进制模式打开文件并直接写入字节

    some_bytes = b'Hello world'
    with open('myfile.txt', 'wb') as f:
        f.write(some_bytes)
    

    请注意,如果以文本模式打开文件,则需要提供正确的编码

    with open('myfile.txt', encoding='utf-16') as f:  # Be sure to use the correct encoding
    

    考虑在运行 Python 时设置 -b-bb 标志以分别引发警告或异常以检测字符串化字节的尝试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 2018-09-21
      • 2019-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多