MD SARFARAZ
MD SARFARAZ

Reputation: 117

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

Upvotes: 0

Views: 169

Answers (3)

Joe T. Boka
Joe T. Boka

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

ljk321
ljk321

Reputation: 16770

You're using count wrong. Try this:

occurence = val.count(sub)

Upvotes: 0

farhawa
farhawa

Reputation: 10398

You are over-complicating it:

open(file).read().count(WORD)

Upvotes: 2

Related Questions