Python - UnicodeEncodeError: 'charmap'编解码器无法对第85-89个字符进行编码:该字符映射到<undefined>。

5

我正在尝试查看是否可以将urllib.request.urlopen()的输出传输到文本文件中以查看。我尝试将输出解码为字符串,以便将其写入文件,但原始输出包含一些无法正确转换为字符串的韩文字。



from urllib.request import urlopen

openU = urlopen(myUrl)
pageH = openU.read()
openU.close()
stringU = pageH.decode("utf-8")

f=open("test.txt", "w+")
f.write(stringU)

在最后一步之前,我没有收到任何错误提示,但是在最后一步时,它显示:

Traceback (most recent call last):  
  File "<stdin>", line 1, in <module>  
  File "C:\Users\Chae\AppData\Local\Programs\Python\Python36\lib\encodings\cp1252.py", line 19, in encode  
  return codecs.charmap_encode(input,self.errors,encoding_table)[0] 
UnicodeEncodeError: 'charmap' codec can't encode characters in position 85-89: character maps to `<undefined>`

有没有办法让字符串也包含韩文,如果不行,如何跳过导致问题的字符并将其余部分写入文件?

1个回答

18

你在意文件编码吗?如果不在意,那么请使用utf-8编码:

f=open("test.txt", "w+", encoding="utf-8")
f.write(stringU)
如果您想将文件编码为cp1252格式(显然是您系统的默认格式),并忽略无法编码的值,请添加errors="ignore":
f=open("test.txt", "w+", errors="ignore")
f.write(stringU)

你是天才吧?!这个 , encoding="utf-8" 帮了我大忙,我为了解决这个问题搜索了好几个小时! - Zac1
2
在使用 encode("utf-8") 后仍然存在完全相同的问题。 - greendino

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接