一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Python词频统计的两种方法代码解析

时间:2021-12-06 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下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)

效果图:

统计的文档

热门栏目