gpt4 book ai didi

python - 网络抓取最常见的名字

转载 作者:太空宇宙 更新时间:2023-11-04 01:59:51 27 4
gpt4 key购买 nike

我需要网络抓取 a web page并找到五个最常见的名字。预期的输出应该是这样的

[
('Anna Pavlovna', 7),
('the prince', 7),
('the Empress', 3),
('Theprince', 3),
('Prince Vasili', 2),
]

我的代码确实计算了最常见的名字,但输出看起来像这样:

 [(<span class="green">Anna Pavlovna</span>, 7),
(<span class="green">the prince</span>, 7),
(<span class="green">the Empress</span>, 3),
(<span class="green">The prince</span>, 3),
(<span class="green">Prince Vasili</span>, 2)]

如何使我的输出看起来像样例输出?

import nltk

from urllib.request import urlopen
from bs4 import BeautifulSoup
html=urlopen('http://www.pythonscraping.com/pages/warandpeace.html')
soup=BeautifulSoup(html,'html.parser')

nameList = soup.findAll("span", {"class":"green"}) # may use bsObj.find_all()


fdist1 = nltk.FreqDist(nameList)
fdist1.most_common(5)

最佳答案

页面显示错误 502 Bad Gateway,但我想我知道你的问题是什么。当您使用 findAll 时,它会为您提供 bs4 元素而不是字符串。因此,您需要使用 obj.get_text() 之类的方法将其转换为字符串。 see documentation

items = soup.findAll("span", {"class": "green"})
texts = [item.get_text() for item in items]
# Now you have the texts of the span elements

顺便说一句,您的代码示例不正确,因为 bsObj 不会被定义。

关于python - 网络抓取最常见的名字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55932642/

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