小编Sam*_*mel的帖子

python 3 - UnicodeEncodeError:“charmap”编解码器无法编码字符(编码,使其位于文件中)

我目前正在尝试获取某个帐户的推文并将其以特定格式写入文件中,但有时该帐户使用表情符号和编解码器之外的其他字符,因此在读取推文时,Python 会崩溃并给出以下错误(它不喜欢的特定字符是希腊字母“\xcf\x87”,如果这有任何帮助的话,尽管我需要一个可以与Python不喜欢的任何字符一起使用的修复程序):

\n\n
UnicodeEncodeError: \'charmap\' codec can\'t encode character \'\\u03c7\' in position 4: character maps to <undefined>\n
Run Code Online (Sandbox Code Playgroud)\n\n

我尝试添加.encode("utf-8")到字符串的末尾,但是当我实际上需要将单词写入不同的行时,最终会将原始文本数据写入文件。这是我到目前为止的代码(代码本身可以工作,因为它读取数据并将其放入我需要的格式,所以我不需要这方面的帮助,只需写入文件部分。) :

\n\n
    with open("LSData.txt", "a") as file:\n        for status in tl:\n            wordList = status.full_text.split(" ")\n            for word in wordList:\n\n                try:\n                    if("http" not in word):\n                        if(word == wordList[0] or\n                           wordList[wordNum-1][len(wordList[wordNum-1])-1] == "." or\n                           wordList[wordNum-1][len(wordList[wordNum-1])-1] == "!" or\n                           wordList[wordNum-1][len(wordList[wordNum-1])-1] == "?"):\n\n                            wordsToAdd = "-"  + word + " " + wordList[wordNum+1] + "\\n"\n                            file.write(wordsToAdd)\n\n                        else:\n                            wordsToAdd = word + " " …
Run Code Online (Sandbox Code Playgroud)

python unicode encoding python-3.x

0
推荐指数
1
解决办法
3248
查看次数

标签 统计

encoding ×1

python ×1

python-3.x ×1

unicode ×1