I’m struggling a little understanding how to use classes effectively. I have written a program which I hope to count the number of occurrences of a phrase or word in a .txt file.
I’m not quite sure how to call the function properly, any help would be much appreciated.
Thanks.
class WordCounter:
def The_Count(self):
print "Counting words..."
txt_doc = open("file")
for line in txt_doc:
if "word" in txt_doc:
word_freq = word_freq + 1
return word_freq
print "Frequency of word: %s" % word_freq
WordCounter.The_Count
you have several problems here, the code you posted isn’t correct python. class methods should take a reference to self as an argument:
you need to initialize word_freq for the case where there are no words to count:
as others have mentioned, you can call your function this way:
It’s not really idiomatic python to wrap these kinds of stateless functions in classes, as you might do in Java or something. I would separate this function into a module, and let the calling class handle the file I/O, etc.