用Python将字符串写入.txt文档,统计每个单词的个数并排序

# 读入文件‘monday.txt’.统计文件中每个单词的数量并且进行输出。
# txt的文本文件为
# Monday.txt的文本内容为
# The pie chart above illustrates apparently the data of people doing exercise and the number of the gyms in a certain
# city of china. Based upon the data,we can see that the statistics of the gyms increased considerably from 1200 billion
# to 1800.

统计单词写入文件的方法:

s = 'The pie chart above illustrates apparently the data of people doing exercise and the number of the gyms in a ' \
    'certain city of china.Based upon the data,we can see that the statistics of the gyms increased considerably ' \
    'from 1200 billion to 1800'
# 写将字符串写入
f = open('Monday.txt','w')
f.write(s)
f.close


# 导入模块
import collections
import re
def fun():
	    with open('Monday.txt', 'r') as fp:
        content = re.split('[,. ]', fp.read())
        print(content)
    b = collections.Counter(content)
    print(b)
    with open('word2.txt', 'w') as result_file:
        for key, value in b.items():
            result_file.write(key + ':' + str(value) + '\n')
fun()

统计单词排序的方法二:

s = 'The pie chart above illustrates apparently the data of people doing exercise and the number of the gyms in a ' \
    'certain city of china.Based upon the data,we can see that the statistics of the gyms increased considerably ' \
    'from 1200 billion to 1800'
# 字符串替换
list1 = s.replace(',',' ')
list2 = list1.replace('.',' ')
print(list2)
# 字符串截取
list3 = list2.split(' ')
print(list3)
# 创建空字典
d = {}
# 遍历列表
for i in list3:
    ss = d.get(i)
    if ss == None:
        d[i] = 1
    else:
        d[i] += 1
print(d)
# 将字典的值变为列表进行排序
d1 = sorted(d.items(),key=lambda x:x[1],reverse=True)
print(d1)
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值