我被要求在网页上搜索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坏网关,但我想我知道你的问题是什么。 当你使用findAll时,它会给你bs4元素而不是字符串。因此,需要将其转换为字符串对象获取文本(). see documentation
顺便说一句,你的代码样本是不正确的,因为bsObj将不会被定义。你知道吗
只要换一行:
对此:
findAll
函数返回一个标记列表,以获取使用text
属性的标记中的文本。你知道吗相关问题 更多 >
编程相关推荐