【问题标题】:Read .txt with emoji characters in python在 python 中读取带有表情符号字符的 .txt
【发布时间】:2018-10-29 13:23:37
【问题描述】:

我尝试阅读带有表情符号的聊天记录,但出现以下错误:

UnicodeDecodeError:“charmap”编解码器无法解码位置 38 中的字节 0x9d:字符映射到

我的代码如下所示:

file_name = "chat_file.txt"
chat = open(chat_file)
chatText = chat.read() # read data
chat.close()
print(chatText)

我很确定这是因为以下元素:❤

如何实现正确的转换格式 // 正确的文件编码是什么,以便 python 可以读取这些元素?

【问题讨论】:

  • 什么版本的python(添加标签)和什么编码(编辑问题)?

标签: python-3.x text iso-8859-1


【解决方案1】:

切勿在未指定编码的情况下打开文本文件。

另外,使用with 块,这些会自动调用.close(),所以你不必这样做。

file_name = "chat_file.txt"

with open(chat_file, encoding="utf8") as chat:
    chat_text = chat.read()

print(chat_text)

iso-8859-1 是传统编码,这意味着它不能包含表情符号。对于表情符号,文本文件必须是 Unicode。 Unicode 最常见的编码是UTF-8

【讨论】:

    猜你喜欢
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    • 2021-10-11
    相关资源
    最近更新 更多