Python: Searching a file for a specific string and outputting the total string count
<p>Attempting to build a search functionality in python that takes an input value/string from the user, searches an external file, and then returns the total count (sum) of that requested value in the file.</p>

<pre><code>if user_search_method == 1:
with open("file.txt", 'r') as searchfile:
    for word in searchfile:
        word = word.lower()
        total = 0
        if user_search_value in word.split():
            total += word.count(user_search_value)
            print total
</code></pre>

<p>When I run this though I get a line-by-line count displayed and not a total sum.  When I add up those lines they are always 1 count short of the actual too.</p>

<p>It feels like there might be something missing from your question, but I will try to get you to where it seems you want to go...</p>

<pre><code>user_search_value = 'test'                     # adding this for completeness of 
                                               # this example
if user_search_method == 1:
    with open("file.txt", 'r') as searchfile:
        total = 0
        for word in searchfile:
            words = word.lower().split()       # breaking the words out, upfront, seems
                                               # more efficient

            if user_search_value in words:
                total += words.count(user_search_value)
        print total                            # the print total statement should be outside the for loop
</code></pre>

python full-text-search