溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何使用python統(tǒng)計(jì)單詞出現(xiàn)次數(shù)

發(fā)布時(shí)間:2020-04-28 09:55:42 來源:億速云 閱讀:1040 作者:小新 欄目:編程語言

這篇文章主要為大家詳細(xì)介紹了如何使用python統(tǒng)計(jì)單詞出現(xiàn)次數(shù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。

python統(tǒng)計(jì)單詞出現(xiàn)次數(shù)

做單詞詞頻統(tǒng)計(jì),用字典無疑是最合適的數(shù)據(jù)類型,單詞作為字典的key, 單詞出現(xiàn)的次數(shù)作為字典的 value,很方便地就記錄好了每個(gè)單詞的頻率,字典很像我們的電話本,每個(gè)名字關(guān)聯(lián)一個(gè)電話號(hào)碼。

下面是具體的實(shí)現(xiàn)代碼,實(shí)現(xiàn)了從importthis.txt文件讀取單詞,并統(tǒng)計(jì)出現(xiàn)次數(shù)最多的5個(gè)單詞。

# -*- coding:utf-8 -*-
import io
import re

class Counter:
    def __init__(self, path):
        """
        :param path: 文件路徑
        """
        self.mapping = dict()
        with io.open(path, encoding="utf-8") as f:
            data = f.read()
            words = [s.lower() for s in re.findall("\w+", data)]
            for word in words:
                self.mapping[word] = self.mapping.get(word, 0) + 1

    def most_common(self, n):
        assert n > 0, "n should be large than 0"
        return sorted(self.mapping.items(), key=lambda item: item[1], reverse=True)[:n]

if __name__ == '__main__':
    most_common_5 = Counter("importthis.txt").most_common(5)
    for item in most_common_5:
        print(item)

執(zhí)行效果:

('is', 10)
('better', 8)
('than', 8)
('the', 6)
('to', 5)

關(guān)于如何使用python統(tǒng)計(jì)單詞出現(xiàn)次數(shù)就分享到這里了,希望以上內(nèi)容可以對大家有一定的參考價(jià)值,可以學(xué)以致用。如果喜歡本篇文章,不妨把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI