gpt4 book ai didi

带有 "lxml"解析器的 Python BeautifulSoup 将长字符串分解为字符

转载 作者:太空狗 更新时间:2023-10-29 21:11:44 26 4
gpt4 key购买 nike

<分区>

我注意到 Python [3.6.5] BeautifulSoup [4.6.0] 与“lxml” [4.2.1] 解析器处理长 bytes 对象与长字符串的方式之间存在奇怪的不一致。 (显然,“long”是 >16,384=2**14 个字符或字节。)

例如,我从麻省理工学院网站下载黑白棋的文本,并以原始(字节)形式和解码为字符串后的形式将其提供给 BS。两个对象的长度相同,因为文档中没有多字节字符。

from bs4 import BeautifulSoup 
import urllib

url = "http://shakespeare.mit.edu/othello/full.html"
html_raw = urllib.request.urlopen(url).read()
html_str = urllib.request.urlopen(url).read().decode("iso-8859-1")

type(html_raw), len(html_raw)
#(<class 'bytes'>, 304769)
type(html_str), len(html_str)
#(<class 'str'>, 304769)

生成的汤对于较短的字符串/字节是相同的,但对于较长的字符串/字节则不同。即,从字符串生成的汤突然开始将单词视为单独的字符,而从字节生成的汤正确处理整个文件:

BeautifulSoup(html_raw[:16410], "lxml")
#... <i>Enter OTHELLO, IAGO, and Attendants with torches</i>
#</blockquote>
#<a></a></body></html>
BeautifulSoup(html_str[:16410], "lxml")
#... <i>Enter OTHELLO, IAGO, and Attendants with torch e s / i &gt;
# / b l o c k q u o t e &gt;
#
# A </i></blockquote></body></html>

这既适用于文档的子集(以上)也适用于整个文档:

BeautifulSoup(html_raw, "lxml")
#...
#<p><i>Exeunt</i></p>
#</blockquote></body>
#</html>

BeautifulSoup(html_str, "lxml")
#...
# p &gt; i &gt; E x e u n t / i &gt; / p &gt;
# / h t m l &gt;
#
#
# </i></blockquote></body></html>

当我使用“html.parser”时,输出之间没有区别。

这是BS实现的bug吗?还是我违反了一些未记录(或记录?)的假设?

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