如何用python统计一个txt文件中某个单词出现的次数

比如搜索123.txt文件中,hello这个单词出现的次数,求帮忙呀

1、首先,定义一个变量,保存要统计的英文文章。

2、接着,定义两个数组,保存文章中的单词,以及各单词的词频。

3、从文章中分割出所有的单词,保存在数组中。

4、然后,计算文章中单词的总数,保存在变量中。

5、用for循环,统计文章中各单词的词频。

6、最后,输出文章中各单词的词频。

7、运行程序,电脑会自动统计输入文章中各单词的词频。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-11-26

"fatway" 的方法简单-美。

还有另一中方法:引入collections的Counter实现更强大的功能

import collections
import re

patt = re.compile("\w+")
counter = collections.Counter(patt.findall(
    open('reparser.py','rt').read()
    ))

# top 10
for word, times in counter.most_common(10):
    print word, times

# find word
counter_dict = dict(counter.most_common(0))
tobefind = 'hello'
print tobefind, counter_dict.get(tobefind, 0)

本回答被提问者和网友采纳
第2个回答  2014-01-02
import re
txt = open("123.txt", "r").read()
print len(re.findall("hello", txt))
第3个回答  2017-06-13
content = {}
wth open("文件") as fr:
for line in fr:
lines = line.strip().split(" ") #假设单词与单词之间,空格做为分隔符
for word in lines:
if word not in content:
content[word] = 0
content[word] += 1
for word,val in content.items():
print '%s:%d\n"%(word,val)
第4个回答  2017-08-03
还有个问题123.txt文件放在哪个文件夹里?