本文介紹python統(tǒng)計(jì)詞頻的幾種方法,供大家參考
目錄
方法一:運(yùn)用集合去重方法
方法二:運(yùn)用字典統(tǒng)計(jì)
方法三:使用計(jì)數(shù)器文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-538403.html
方法一:運(yùn)用集合去重方法
def word_count1(words,n):
word_list = []
for word in set(words):
num = words.counts(word)
word_list.append([word,num])
word_list.sort(key=lambda x:x[1], reverse=True)
for i in range(n):
word, count = word_list[i]
print('{0:<15}{1:>5}'.format(word, count))
說(shuō)明:運(yùn)用集合對(duì)文本字符串列表去重,這樣統(tǒng)計(jì)詞匯不會(huì)重復(fù),運(yùn)用列表的counts方法統(tǒng)計(jì)頻數(shù),將每個(gè)詞匯和其出現(xiàn)的次數(shù)打包成一個(gè)列表加入到word_list中,運(yùn)用列表的sort方法排序,大功告成。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-538403.html
方法二:運(yùn)用字典統(tǒng)計(jì)
def word_count2(words,n):
counts = {}
for word in words:
if len(word) == 1:
continue
else:
counts[word] = counts.get(word, 0) + 1
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True)
for i in range(n):
word, count = items[i]
print("{0:<15}{1:>5}".format(word, count))
方法三:使用計(jì)數(shù)器
def word_count3(words,n):
from collections import Counter
counts = Counter(words)
for ch in "": # 刪除一些不需要統(tǒng)計(jì)的元素
del counts[ch]
for word, count in counts.most_common(n): # 已經(jīng)按數(shù)量大小排好了
print("{0:<15}{1:>5}".format(word, count))
到了這里,關(guān)于Python統(tǒng)計(jì)詞頻的幾種方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!