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)

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值