最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Python词频统计的两种方法代码解析
时间:2022-06-25 01:32:22 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下Python词频统计的两种方法代码解析,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
统计文件里每个单词的个数
思路:
分别统计文档中的单词,与出现的次数
用两个列表将其保存起来,最后再用zip()函数连接输出**
想法成立开始实践
方法一:
# 导入文件
with open("passage.txt", 'r') as file:
dates = file.readlines()
# 处理
words = []
for i in dates:
words += i.replace("n", "").split(" ") # 用空字符来代替换行 words +是为了不被覆盖无+将只有最后一条数据
# print(i.replace("n","").split(" "))
setWords = list(set(words)) # 集合自动去重
num = [] # 统计一个单词出现的次数
for k in setWords:
count = 0
for j in words:
if k == j:
count = count + 1
num.append(count)
print(num)
print(setWords)
# 输出
for x, y in zip(setWords, num): # 将两个列表用zip结合
print(x + ":" + str(y))、
效果图:
方法二:
此方法用来字典,较前一个相对简洁一点
# 导入
with open("passage.txt", 'r') as file:
dates = file.readlines()
# 处理
words = []
for i in dates:
words += i.replace("n", "").split(" ")
# print(i.replace("n","").split(" "))
# setWords=list(set(words)) #可以不用这个
print(words)
print("-" * 40)
# print(setWords)
diccount = dict()
for i in words:
if (i not in diccount):
diccount[i] = 1 # 第一遍字典为空 赋值相当于 i=1,i为words里的单词
# print(diccount)
else:
diccount[i] = diccount[i] + 1 # 等不在里面的全部遍历一遍赋值就都在里面了,我们再来记数
print(diccount)
效果图:
统计的文档
相关文章
- 超自然行动组礼包兑换码有哪些 2025最新可用兑换码合集 11-05
- 逃离鸭科夫怎么刷刀 逃离鸭科夫刷刀方法介绍 11-05
- 逃离鸭科夫怎么解锁农场小镇 农场小镇解锁攻略 11-05
- 梦幻消除战座无虚席有什么玩法技巧 11-05
- 适合跨年的句子 11-05
- 忘川风华录周瑜怎么培养 11-05


