Reputation: 117
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
Upvotes: 0
Views: 169
Reputation: 6589
If you want to know how many times the word Date:
occurs in the text file, this is one way to do it:
myfile = open("C:\\Users\\md_sarfaraz\\Desktop\\ctl_Files.txt", "r").read()
sub = "Date:"
occurence = myfile.count(sub)
print occurence
Upvotes: 0