Python regular expression search text file count substring
<p>I am attempting to use a regular expression statement in python to search a text file and count the number of times a user defined word appears. When I run my code though, 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 'apple' exists 56 times in the text file. Appearing in 20 of the total 63 lines of text. When I run my code the console prints '20' for the count of 'apple' instead of the correct '56'. </p>

<p>I thought by using the re.findall() method it would fix this, but it has not.</p>

<pre><code>import re

#If user selects Regular Expressions as their search method
elif user_search_method == "2":
    print "\n&gt;&gt;&gt; You selected the Regular Expressions search method"
    f = open(filename, 'r')
    words = sum(1 for w in f if re.findall(user_search_value, w, re.M|re.I))
    f.close()
    print("Your search value of '%s' appears %s times in this file" % (user_search_value, words))
</code></pre>

<p>You're just adding 1 if it matches, I guess you don't want the search to go over lines, so you can do this:</p>

<pre><code>words = sum(len(re.findall(user_search_value, w, re.M|re.I)) for w in f)
</code></pre>

python regex full-text-search