【问题标题】:counting words inside a webpage计算网页内的单词
【发布时间】:2018-02-26 12:46:41
【问题描述】:

我需要使用 python3 计算网页内的单词。我应该使用哪个模块? urllib?

这是我的代码:

def web():
    f =("urllib.request.urlopen("https://americancivilwar.com/north/lincoln.html")
    lu = f.read()
    print(lu)

【问题讨论】:

  • 上面的代码只是为了阅读网页而不是计数,但我只是想先访问不同的单词。
  • 你可以使用 bs4 并获取所有文本,然后找到它的len
  • 对于初学者,您应该从 f =("urllib 中删除 (",使其显示为 f = urllib
  • 我的代码甚至给了我 html 代码,所以我需要删除它们。我该怎么做?

标签: python-3.x urllib2 urllib urllib3


【解决方案1】:

通过以下自我解释的代码,您可以获得一个很好的起点来计算网页中的单词:

import requests
from bs4 import BeautifulSoup
from collections import Counter
from string import punctuation

# We get the url
r = requests.get("https://en.wikiquote.org/wiki/Khalil_Gibran")
soup = BeautifulSoup(r.content)

# We get the words within paragrphs
text_p = (''.join(s.findAll(text=True))for s in soup.findAll('p'))
c_p = Counter((x.rstrip(punctuation).lower() for y in text_p for x in y.split()))

# We get the words within divs
text_div = (''.join(s.findAll(text=True))for s in soup.findAll('div'))
c_div = Counter((x.rstrip(punctuation).lower() for y in text_div for x in y.split()))

# We sum the two countesr and get a list with words count from most to less common
total = c_div + c_p
list_most_common_words = total.most_common() 

如果您想要例如前 10 个最常用的单词:

total.most_common(10)

在这种情况下输出:

In [100]: total.most_common(10)
Out[100]: 
[('the', 2097),
 ('and', 1651),
 ('of', 998),
 ('in', 625),
 ('i', 592),
 ('a', 529),
 ('to', 529),
 ('that', 426),
 ('is', 369),
 ('my', 365)]

【讨论】:

  • 我不知道谁让我对这个问题投了反对票。无缘无故投反对票。
  • 不是我。顺便说一句,如果您觉得我的回答有用,请考虑支持/接受它。
  • 由于声誉不足,我的投票没有被计算在内。但是,你有我的赞成票。我只是在徘徊,如果我可以检查 python 代码是否抄袭,但我没有得到任何人的任何回应。
  • 您可以接受在赞成票和反对票下打勾的答案
  • 我发现上述方法可能输出不精确的数字,因为段落可以在 div 内,反之亦然。不知道它是如何工作的,但我在网上找到了一个有趣的工具来检查网站内的字数:wordcounter.net/website-word-count
猜你喜欢
  • 2011-03-29
  • 1970-01-01
  • 2017-06-29
  • 1970-01-01
  • 2010-09-17
  • 2022-01-06
  • 1970-01-01
  • 2018-01-21
  • 1970-01-01
相关资源
最近更新 更多