欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python統(tǒng)計(jì)詞頻的幾種方法小結(jié)

 更新時(shí)間:2023年03月01日 15:55:09   作者:西西弗斯推石頭  
本文主要介紹了Python統(tǒng)計(jì)詞頻的幾種方法小結(jié),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

本文介紹python統(tǒng)計(jì)詞頻的幾種方法,供大家參考

方法一:運(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))

說明:運(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方法排序,大功告成。

方法二:運(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ì)詞頻的幾種方法小結(jié)的文章就介紹到這了,更多相關(guān)Python統(tǒng)計(jì)詞頻內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論