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>You are printing the <code>total</code> in each iteration, you have to put it out of <code>for</code> loop. Also you can do this job more pythonic, using one generator expression:</p>

<pre><code>if user_search_method == 1:
    with open("file.txt") as searchfile:
        total = sum(line.lower().split().count(user_search_value) for line in searchfile)
    print total
</code></pre>

python full-text-search