gpt4 book ai didi

Python - 将表情符号字符写入日志文件

转载 作者:行者123 更新时间:2023-12-05 06:37:37 32 4
gpt4 key购买 nike

我在将表情符号字符写入 .log 文件时遇到困难。这是我的代码的相关片段:

with open("testLog.log", "a") as myfile:
print (message.content) #print to console - for debugging only
print (message.content.encode('utf-8')) #print to console - for debugging only
myfile.write(message.content)

这是当 message.content = 'hello there! 时输出到我的控制台的内容! 👍'

hello there! 👍                              
b'hello there! \xf0\x9f\x91\x8d'
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\path\to\file\file.py", line 29, in on_message
myfile.write(message.content)
File "C:\Python\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\U0001f44d' in position 13: character maps to <undefined>

我环顾四周并尝试了一些解决方案,但无济于事。这个错误是由于我的日志文件是如何编码的吗?如果是这样,我如何更改编码以允许使用 utf-8 字符?

一个允许但不是优选的解决方案是一种检测字符串中是否存在这些字符的方法,这样我就可以不将内容写入日志。

最佳答案

这应该可以解决您的问题。来自:https://stackoverflow.com/a/43813727/6579239

with open("testLog.log", "a") as myfile:
print (message.content) #print to console - for debugging only
print (message.content.encode('ascii', 'ignore').decode('ascii')) #print to console - for debugging only
myfile.write(message.content)

关于Python - 将表情符号字符写入日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47373515/

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