gpt4 book ai didi

python - 使用 Python 读取 .htm 文件时的编码问题

转载 作者:行者123 更新时间:2023-11-27 22:58:45 24 4
gpt4 key购买 nike

我正在尝试使用 Python 读取大量 .htm 文件。为此,我使用了以下内容:

HtmlFile = codecs.open(file, 'r')
text = BeautifulSoup(HtmlFile.read()).text

但是,这会导致以下错误:

UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 411: 
character maps to <undefined>

因此,我尝试使用 utf-8 进行编码,如下所示:

HtmlFile = codecs.open(file, 'r', encoding='utf-8')
text = BeautifulSoup(HtmlFile.read()).text

然后我得到了这个错误:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 4565: 
invalid start byte

我尝试遵循 here 的建议,但没有帮助。任何帮助将不胜感激!

最佳答案

我做了一些研究,发现这是 Microsoft 使用 CP1252 编码生成的文件的问题,但是有些内容没有正确提取。鉴于以下情况:

<meta http-equiv=Content-Type content="text/html; charset=windows-1252">
<meta name=Generator content="Microsoft Word 15 (filtered)">

在您的 html 文件中,这似乎很有可能。

根据这个answer ,如果您对该示例使用 Latin-1 编码,它可能会有所帮助:

HtmlFile = codecs.open(file, 'r', encoding='latin-1')
text = BeautifulSoup(HtmlFile.read()).text

让我知道这是否可行。请注意,Latin-1 并不具有 Microsoft 编码所具有的所有字符。

关于python - 使用 Python 读取 .htm 文件时的编码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53824656/

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