3 回答

TA貢獻1803條經驗 獲得超6個贊
如果您使用的是Python的早期版本,或者您有充分的理由推出自己的單詞計數器(我想聽聽它!),則可以嘗試使用以下方法dict。
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> word_list = ['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats', 'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and', 'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.', 'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cats', 'have', 'bright', 'black', 'eyes;', 'They', 'like', 'to', 'practise', 'their', 'airs', 'and', 'graces', 'And', 'wait', 'for', 'the', 'Jellicle', 'Moon', 'to', 'rise.', '']
>>> word_counter = {}
>>> for word in word_list:
... if word in word_counter:
... word_counter[word] += 1
... else:
... word_counter[word] = 1
...
>>> popular_words = sorted(word_counter, key = word_counter.get, reverse = True)
>>>
>>> top_3 = popular_words[:3]
>>>
>>> top_3
['Jellicle', 'Cats', 'and']
熱門提示:每當您要使用這樣的算法時,交互式Python解釋器就是您的朋友。只需將其鍵入并觀看即可,并檢查整個過程中的元素。

TA貢獻1864條經驗 獲得超6個贊
在Python 2.7及更高版本中,有一個名為Counter的類可以幫助您:
from collections import Counter
words_to_count = (word for word in word_list if word[:1].isupper())
c = Counter(words_to_count)
print c.most_common(3)
結果:
[('Jellicle', 6), ('Cats', 5), ('And', 2)]
我對編程很陌生,所以請嘗試以最準系統的方式進行。
您可以改用字典來完成此操作,其中的鍵是一個單詞,值是該單詞的計數。首先遍歷單詞,如果不存在則將其添加到字典中;否則,如果單詞存在,則增加單詞的計數。然后,要找到O(n*log(n))前三個元素,可以使用簡單的排序算法并從結果中獲取前三個元素,也可以使用O(n)僅記住前三個元素即可掃描列表的算法。
對于初學者來說,一個重要的觀察結果是,通過使用為此目的而設計的內置類,您可以節省很多工作和/或獲得更好的性能。熟悉標準庫及其提供的功能是很好的。

TA貢獻1843條經驗 獲得超7個贊
僅返回包含最常用單詞的列表:
from collections import Counter
words=["i", "love", "you", "i", "you", "a", "are", "you", "you", "fine", "green"]
most_common_words= [word for word, word_count in Counter(words).most_common(3)]
print most_common_words
打?。?/p>
['you', 'i', 'a']
“ most_common(3)”中的3 ,指定要打印的項目數。 Counter(words).most_common()返回一個元組列表,每個元組以單詞為第一個成員,頻率為第二個成員。元組按單詞的頻率排序。
`most_common = [item for item in Counter(words).most_common()]
print(str(most_common))
[('you', 4), ('i', 2), ('a', 1), ('are', 1), ('green', 1), ('love',1), ('fine', 1)]`
“ the word for word, word_counter in”僅提取元組的第一個成員。
添加回答
舉報