[英]counting occurence of a word in a text file using python
I'm tring to count the occurence of a word in a text file. 我正在努力计算一个文本文件中单词的出现次数。
sub = 'Date:'
#opening and reading the input file
#In path to input file use '\' as escape character
with open ("C:\\Users\\md_sarfaraz\\Desktop\\ctl_Files.txt", "r") as myfile:
val=myfile.read().replace('\n', ' ')
#val
#len(val)
occurence = str.count(sub, 0, len(val))
I'm getting this error :-- 我收到此错误消息:-
>>> occurence = str.count('Date:', 0,len(val))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: expected a character buffer object
>>> occurence = str.count('Date:', 0,20)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: expected a character buffer object
您过于复杂了:
open(file).read().count(WORD)
You're using count
wrong. 您使用的
count
错误。 Try this: 尝试这个:
occurence = val.count(sub)
If you want to know how many times the word Date:
occurs in the text file, this is one way to do it: 如果您想知道单词“
Date:
在文本文件中出现了多少次,这是一种处理方法:
myfile = open("C:\\Users\\md_sarfaraz\\Desktop\\ctl_Files.txt", "r").read()
sub = "Date:"
occurence = myfile.count(sub)
print occurence
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.