Python学习:统计文件中每个单词的个数

  • 文件中的内容
    请添加图片描述

通过python程序将文件中的单词数量统计出来

请添加图片描述

  • 代码:
# -*- coding: utf-8 -*-
"""
功能:统计文件中单词个数
作者:zwh
日期:2021年12月7日
"""

test = open('test.txt')  
# 利用open()函数将test文件中的内容导入到test列表中.
words_td = []

for word in test:
    words_td.append((word.strip()).split(' ')) 
# split()函数将单词以空格为界切割
# print(words_td)     # 打印二维列表

words_od = []
for i in range(len(words_td)):
    for j in range(len(words_td[i])):
        words_od.append(words_td[i][j])
print(f'test文件中的所有单词:\n{words_od}')  
# 二位列表转一维列表

# 将一维列表中的单词去重  set()去重函数
diff_words = list(set(words_od))
# print(diff_words)


counts = []  # 创建统计单词个数列表
for c in range(len(diff_words)):
    counts.append(0)

for w_o in range(len(words_od)):
    for d_w in range(len(diff_words)):
        if diff_words[d_w] == words_od[w_o]:
            counts[d_w] = counts[d_w] + 1
# print(f'{diff_words}\n{counts}')
# 输出统计结果


for i in range(len(diff_words)):
    for j in range(len(counts)):
        if i == j:
            print(f'test文件中有单词{diff_words[i]}:{counts[j]}个')
# {f'内容{输出内容}'}这种写法相当于{'内容'.format(输出内容)}
            break


print(f'test文件中共有{sum(counts)}个单词。')



心得:

学习python,不能急于求成。要想学好它,那得多练,在学习的途中,寻找乐趣。

  • 10
    点赞
  • 82
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值