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>

<pre><code>if user_search_method == 1:    
  total = 0    
  with open('file.txt') as f:
    for line in f:
      total += line.casefold().split().count(user_search_value.casefold())
  print(total)
</code></pre>

<p>This is probably what you wanted doing.</p>

python full-text-search