统计一篇英文文章单词个数,取出出现频次前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 Counterwith open('1.txt', 'r', ) as f:words = f.read()                         # 将文件的内容全部读取成一个字符串count = Counter(re.split(r"\W+", words))  # 以单词为分隔result = count.most_common(10)                # 统计最常使用的前10个
print(result)


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部