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>As I mentioned in the comment above, after playing with this for a (long) while I figured it out.  My code is below.</p>

<pre><code>#read file
f = open(filename, "r")
lines = f.readlines()
f.close()
#looking for patterns
for line in lines:
    line = line.strip().lower().split()
    for words in line:
        if words.find(user_search_value.lower()) != -1:
            count += 1
print("\nYour search value of '%s' appears %s times in this file" % (user_search_value, count))
</code></pre>

python python-2.7 string-matching