在 python 中阅读带有表情符号字符的 .txt

Read .txt with emoji characters in python

我尝试读取其中包含表情符号的聊天记录,但出现以下错误:

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

我的代码如下所示:

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

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

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

从不 打开未指定编码的文本文件。

此外,使用 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.