统计某一个单词的个数
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}