Answer: With respect the question of 'why wrong output' - You need to iterate through every word in your line.
Suggestion:
When you are search for multiple words, you can have them in a dict and store the count as the value of the corresponding dict key.
Content of file:
Hi this is hello
Hello is my name
Then
text_file.read()
will give,
['Hi this is hello\n', 'Hello is my name\n']
text_file.read().splitlines()
['Hi this is hello', 'Hello is my name']
Then split every line in your lines,
lines = map(str.split,text_file.read().splitlines())
[['Hi', 'this', 'is', 'hello'], ['Hello', 'is', 'my', 'name']]
On chaining the iterable,
it.chain.from_iterable(map(str.split,text_file.read().splitlines()))
['Hi', 'this', 'is', 'hello', 'Hello', 'is', 'my', 'name']
And,
search=['dog','cat'] # the words that you need count
search = dict.fromkeys(search,0) # will give a dict as {'dog':0,'cat':0}
Therefore for your problem,
def main():
text_file = open("textfile.txt", "r")
search=['cat','dog']
search = dict.fromkeys(search,0)
import itertools as it
res=dict()
for word in it.chain.from_iterable(map(str.split,text_file.read().splitlines())):
if word.lower() in search:
search[word.lower()]=search[word.lower()]+1
for word,count in search.iteritems():
print('the word %s occurs %d times'%(word,count))
This get the count of case sensitive words too!
Hope it helps!