gpt4 book ai didi

python - UnicodeEncodeError - 在 Spyder 中有效,但从终端执行时无效

转载 作者:太空宇宙 更新时间:2023-11-03 18:40:20 24 4
gpt4 key购买 nike

我正在使用 BeautifulSoup 来解析一些 html,并使用 Spyder 作为我的编辑器(顺便说一句,这都是出色的工具!)。代码在 Spyder 中运行良好,但是当我尝试从终端执行 .py 文件时,出现错误:

file =  open('index.html','r')
soup = BeautifulSoup(file)
html = soup.prettify()
file1 = open('index.html', 'wb')
file1.write(html)

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa9' in position 5632: ordinal not in range(128)

我在 Linux 服务器上运行 OPENSUSE,并使用 zypper 安装了 Spyder。有人有什么建议可能是什么问题吗?非常感谢。

最佳答案

这是因为在输出结果(即将其写入文件)之前,您必须先对其进行编码:

file1.write(html.encode('utf-8'))

看到每个文件都有一个属性file.encoding。引用文档:

file.encoding

The encoding that this file uses. When Unicode strings are written to a file, they will be converted to byte strings using this encoding. In addition, when the file is connected to a terminal, the attribute gives the encoding that the terminal is likely to use (that information might be incorrect if the user has misconfigured the terminal). The attribute is read-only and may not be present on all file-like objects. It may also be None, in which case the file uses the system default encoding for converting Unicode strings.

看到最后一句了吗? soup.prettify 返回一个 Unicode 对象并给出此错误,我很确定您使用的是 Python 2.7,因为它的 sys.getdefaultencoding()ascii.

希望这有帮助!

关于python - UnicodeEncodeError - 在 Spyder 中有效,但从终端执行时无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20643032/

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