Python統(tǒng)計詞頻的幾種方法小結
更新時間:2023年03月01日 15:55:09 作者:西西弗斯推石頭
本文主要介紹了Python統(tǒng)計詞頻的幾種方法小結,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
本文介紹python統(tǒng)計詞頻的幾種方法,供大家參考
方法一:運用集合去重方法
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))
說明:運用集合對文本字符串列表去重,這樣統(tǒng)計詞匯不會重復,運用列表的counts方法統(tǒng)計頻數,將每個詞匯和其出現的次數打包成一個列表加入到word_list中,運用列表的sort方法排序,大功告成。
方法二:運用字典統(tǒng)計
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))
方法三:使用計數器
def word_count3(words,n): from collections import Counter counts = Counter(words) for ch in "": # 刪除一些不需要統(tǒng)計的元素 del counts[ch] for word, count in counts.most_common(n): # 已經按數量大小排好了 print("{0:<15}{1:>5}".format(word, count))
到此這篇關于Python統(tǒng)計詞頻的幾種方法小結的文章就介紹到這了,更多相關Python統(tǒng)計詞頻內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python通過pillow識別動態(tài)驗證碼的示例代碼
在上網時,經常會遇到驗證碼,本次試驗將帶領大家認識驗證碼的一些特性,并利用 Python 中的 pillow 庫完成對驗證碼的破解。感興趣的可以了解一下2021-11-11