python统计字符在文件中出现的次数_Python统计字符出现次数(Counter包)以及txt文件写入...

#-*- coding: utf-8 -*-#spyder (python 3.7)

1. 统计字符(可以在jieba分词之后使用)

from collections importCounterfrom operator importitemgetter#txt_list可以写成函数参数进行导入

txt_list = ['千古','人间','人间','龙','龙','龙','哈哈哈','人才','千古','千古']

c=Counter()for x intxt_list:if len(x) >= 1:if x == '\r\n' or x == '\n' or x == ' ':continue

else:

c[x]+= 1

print('常用词频统计结果: \n')for (k, v) in c.most_common(4): #打印排名前四位

print('%s%s %s %d' % (' ' * (3 ), k, '*' * 3, v))#按照词频数从大到小打印

d = sorted(c.items(),key=itemgetter(1),reverse =True)for ss,tt ind:

out_words=ss + '\t' +str(tt)print(out_words)

2. 多次覆盖,循环写入文件

#写入文件,多次写入,后一次覆盖前一次,但是out_words本身是在叠加的#即:第一次写入的是:千古\t3\n;第二次写入的是:千古\t3\n龙\t3\n,覆盖上一次的数据;#第三次是:千古\t3\n龙\t3\n人间\t2\n,继续覆盖上一次的数据

out_words = ''

for ss,tt ind:

out_words=out_words + ss + '\t' + str(tt) + '\n'with open(r".\sss.txt", "w",encoding='utf-8') as f:

f.write(out_words+'\n')

比如,循环两次的结果是:

1468269-20191016222751323-1357691422.png

3. 一次性写入文件,中间不会覆盖和多次写入;但是如果重复运行代码,则会覆盖之前的全部内容,一次性重新写入所有新内容

out_words = ''

for ss,tt ind:

out_words=out_words + ss + '\t' + str(tt) + '\n'with open(r".\ttt.txt", "w",encoding='utf-8') as f:

f.write(out_words+'\n')

1468269-20191016222730634-1775423973.png

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值