Python search text file and count occurrences of a specified string
<p>I am attempting to use python to search a text file and count the number of times a user defined word appears. But when I run my code below instead of getting a sum of the number of times that unique word appears in the file, I am getting a count for the number lines within that file contain that word. </p>

<p>Example: the word 'bob' exists 56 times in the text file, appearing in 19 of the total 63 lines of text.  When I run my code the console prints '19'.</p>

<p>I am guessing I need to do something different with my split method?  I am running Python 2.7.10.</p>

<pre><code>user_search_value = raw_input("Enter the value or string to search for: ")

count = 0    

with open(file.txt, 'r') as f:
    for word in f.readlines():
        words = word.lower().split()
        if user_search_value in words:
            count += 1
    print count
</code></pre>

<p>One way to do this would be to loop over the words after you split the line and increment <code>count</code> for each matching word:</p>

<pre><code>user_search_value = raw_input("Enter the value or string to search for: ")

count = 0    

with open(file.txt, 'r') as f:
    for line in f.readlines():
        words = line.lower().split()
        for word in words:
            if word == user_search_value:
                count += 1
print count
</code></pre>

python python-2.7 string-matching