python统计单词个数算法_统计一篇英文文章单词个数,取出出现频次前10的单词(Python实现)...
題目: 用python實現統計一篇英文文章內每個單詞的出現頻率,并返回出現頻率最高的前10個單詞及其出現次數。
常規解法
怎么判定單詞?
1 不是字母的特殊字符作為分隔符分割字符串 (避免特殊字符的處理不便,全部替換成””)
2 正則分割
3 遍歷字符串,取每個word
4 正則匹配
怎么統計個數?
將wordlist的word和word的個數放入dict,排序
import re
with open('1.txt', 'r') as f:
word_dict = {} # 用于統計 word:個數
word_list = [] # 用于存放所有單詞
for line in fd.readlines():
for word in line.strip().split(" "):
word_list.append(re.sub(r"[^a-z]+", "", word.lower()))
word_sets = list(set(word_list)) # 確保唯一
word_dict = {word: word_list.count(word) for word in word_sets if word}
result = sorted(word_dict.items(), key=lambda d: d[1], reverse=True)[:10]
print(result)
利用collections模塊
import re
from collections import Counter
with open('1.txt', 'r', ) as f:
words = f.read() # 將文件的內容全部讀取成一個字符串
count = Counter(re.split(r"\W+", words)) # 以單詞為分隔
result = count.most_common(10) # 統計最常使用的前10個
print(result)
總結
以上是生活随笔為你收集整理的python统计单词个数算法_统计一篇英文文章单词个数,取出出现频次前10的单词(Python实现)...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 刹车失灵?福特全球召回近130万辆汽车
- 下一篇: websocket python爬虫_p