python統(tǒng)計文章中單詞出現次數實例
python統(tǒng)計單詞出現次數
做單詞詞頻統(tǒng)計,用字典無疑是最合適的數據類型,單詞作為字典的key, 單詞出現的次數作為字典的 value,很方便地就記錄好了每個單詞的頻率,字典很像我們的電話本,每個名字關聯一個電話號碼。
下面是具體的實現代碼,實現了從importthis.txt文件讀取單詞,并統(tǒng)計出現次數最多的5個單詞。
# -*- coding:utf-8 -*-import ioimport 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)
知識點補充:
1、如何正確讀寫文件
2、如何對數據進行排序
3、字典數據類型的運用
4、正則表達式的運用
到此這篇關于python統(tǒng)計文章中單詞出現次數實例的文章就介紹到這了,更多相關python統(tǒng)計單詞出現次數內容請搜索好吧啦網以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
