簡體   English   中英

返回網站中最常見的單詞,使單詞數> 5

[英]Return most common words in a website, such that word count >5

我是python的新手。 我有一個簡單的程序來查找一個單詞在網站中使用的次數。

opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]

url = 'https://en.wikipedia.org/wiki/Wolfgang_Amadeus_Mozart'
ourUrl = opener.open(url).read()
soup = BeautifulSoup(ourUrl)
dem = soup.findAll('p') #find paragraphs
word_counts = Counter()
stopwords = frozenset(('A', 'AN', 'THE'))


for i in dem:    # loop for each para
    words = re.findall(r'\w+', i.text)
    cap_words = [word.upper() for word in words if not word.upper() in stopwords]
    word_counts.update(cap_words)

print word_counts

事實是,這個腳本提供了很多只使用一次的單詞。 如何更新腳本以使包含的單詞至少包含5個字數。

另外,如何排列前5個最常用的單詞,比如word1,word2,word3 ......等。

如何更新腳本以便包含單詞,至少包含5個字數。

您可以按如下方式過濾計數器: filter(lambda x: x[1] > 5, word_counts.iteritems())

filter()接受一個函數和一個iterable,將函數應用於iterable的每個元素,如果函數返回True ,則只在輸出中包含該項。 iteritems()返回一個生成器,它通過字典產生鍵值對。

我如何安排前5個最常用的單詞,比如說word1,word2,word3 ....等等。

有一個most_common(n)計數器功能。 請參見http://docs.python.org/2/library/collections.html

嘗試: print word_counts.most_common(5)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM