python3.3.2 如何统计文本文件中出现的每个单词出现的次数,单词之间使用空格隔开

python3.3.2 如何统计文本文件中出现的每个单词数目,单词之间使用空格隔开
如下面这段英文
test.txt里面包含以下内容
hello feel love I you test test one two three
worlds
Pursuing further research may involve at a subsequent stage
the acquisition of a doctoral degree hello feel love I you test test one two three
Pursuing further research may involve
at a subsequent stage
the acquisition of a doctoral degree

如何统计这个文件中的每个单词出现的次数

第1个回答  推荐于2018-05-10
很简答的东东

import re
import collections

print( collections.Counter( re.findall( '\w+' ,open( 'test.txt' ).read( ) ) ) )

还是多看看资料吧,这个是官方的标准答案本回答被提问者采纳
第2个回答  2014-03-20
wordtext=open(r'test.txt')
countdict={}
for line in wordtext:
for word in line.split():
word=word.lower()
if word in countdict:
countdict[word]+=1
else:
countdict[word]=1
for word in sorted(countdict):
print("%s:%d"%(word,countdict[word]))

统计文本文件test.txt中单词个数,不区分大小写,单词必须用空格分开,不能有其它字符
这个问题能不能换个分类,在这个分类无法使用格式代码追问

如何将结果写入到文件中呢?

追答

python 2.x将最后的print语句改为
print >>result.txt,"%s:%d"%(word,countdict[word])
python 3.x版本,则改为
print("%s:%d"%(word,countdict[word]),file=open("result.txt"))
其中result.txt为要写入的文件

本回答被网友采纳
相似回答