python统计个数的函数_python统计文件中的字符个数

统计某一个单词的个数

test6.txt 内容

eegin

a aa aaa aaaa

end

eegin

e ee eee eeee

end

eegin

c cc ccc cccc

end

方法1:

import re

with open('test6.txt') as f1:

message=''

for line in f1:

message+=line

counter=re.findall('a',message)

print(len(counter))

结果:

10

如果遇到像test6.txt所示的,一组词换行的,我们需要用到rstrip()函数

test6.txt 内容

我喜欢 我不喜欢 我到底喜

不喜欢 我可能很喜欢 是吗 我喜

欢吗

方法2:

#coding=utf-8

import re

with open('test6.txt') as f1:

message=''

for line in f1:

message+=line.rstrip()

counter=re.findall('喜欢',message)

print(len(counter))

结果:

5

上面只是统计1个词,如果遇到统计多个词,则需要用到字典

test6.txt 内容

我喜欢 我不喜欢 我到底喜

不喜欢 我可能很喜欢 是吗 我喜

欢吗

方法3:

#coding=utf-8

import re

word_num={}

with open('test6.txt') as f1:

message=''

for line in f1:

message+=line.rstrip()

word_num['喜欢']=len(re.findall('喜欢',message))

word_num['不']=len(re.findall('不',message))

word_num['你']=len(re.findall('你',message))

print(word_num)

结果:

{'喜欢': 5, '不': 2, '你': 0}

如果我想统计文件里的所有词出现的次数

test6.txt 内容

喜欢:不喜欢:喜欢:不喜欢

我:他:你

方法4:

#coding=utf-8

import re

word_num={}

with open('test6.txt') as f1:

message=''

for line in f1:

message+=line

words=re.split(':|\n',message) #python的内建函数split() 和re.split() 函数区别,后者支持多个分割符

for word in words:

word_num[word]=len(re.findall(word,message))

print(word_num)

结果:

{'喜欢': 4, '不喜欢': 2, '我': 2, '他': 1, '你': 1}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值