python中统计单词出现的次数_python统计文章中单词出现次数实例
python統計單詞出現次數
做單詞詞頻統計,用字典無疑是最合適的數據類型,單詞作為字典的key, 單詞出現的次數作為字典的 value,很方便地就記錄好了每個單詞的頻率,字典很像我們的電話本,每個名字關聯一個電話號碼。
下面是具體的實現代碼,實現了從importthis.txt文件讀取單詞,并統計出現次數最多的5個單詞。
# -*- 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)
執行效果:
('is', 10)
('better', 8)
('than', 8)
('the', 6)
('to', 5)
知識點補充:
1、如何正確讀寫文件
2、如何對數據進行排序
3、字典數據類型的運用
4、正則表達式的運用
到此這篇關于python統計文章中單詞出現次數實例的文章就介紹到這了,更多相關python統計單詞出現次數內容請搜索我們以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持我們!
本文標題: python統計文章中單詞出現次數實例
本文地址: http://www.cppcns.com/jiaoben/python/301688.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的python中统计单词出现的次数_python统计文章中单词出现次数实例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: bootstrap下拉选择框选中事件_C
- 下一篇: eas 在linux下安装_Linux下