python - 在文件中查找单词的出现 [英] python - find the occurrence of the word in a file
本文介绍了python - 在文件中查找单词的出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图找到文件中出现的字数。我有一个文本文件( TEST.txt
)文件的内容如下:
ashwin programmer india
amith programmer india
:
{'ashwin':1,'programmer':2,'india':2,'amith':1}
我使用的代码是:
<$
word = line(line.split())
打印字
pre>
code> 我得到的结果是:
Counter({'amith':1,'programmer':1,'india':1} )
任何人都可以帮助我吗?提前感谢。
解决方案使用计数器的更新
方法。示例:
来自集合import counter
data ='''\
ashwin程序员印度
amith programmer india'''
c = Counter()
for data.splitlines():
c.update(line.split )
print(c)
输出:
计数器({'india':2,'programmer':2,'amith':1,'ashwin':1})
I am trying to find the count of words that occured in a file. I have a text file (TEST.txt
) the content of the file is as follows:
ashwin programmer india
amith programmer india
The result I expect is:
{ 'ashwin':1, 'programmer ':2,'india':2, 'amith ':1}
The code I am using is:
for line in open(TEST.txt,'r'):
word = Counter(line.split())
print word
The result I get is:
Counter({'ashwin': 1, 'programmer': 1,'india':1})
Counter({'amith': 1, 'programmer': 1,'india':1})
Can any one please help me? Thanks in advance .
解决方案 Use the update
method of Counter. Example:
from collections import Counter
data = '''\
ashwin programmer india
amith programmer india'''
c = Counter()
for line in data.splitlines():
c.update(line.split())
print(c)
Output:
Counter({'india': 2, 'programmer': 2, 'amith': 1, 'ashwin': 1})
这篇关于python - 在文件中查找单词的出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文