简体   繁体   中英

Python: Searching a file for a specific string and outputting the total string count

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.

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

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.

You are printing the total in each iteration, you have to put it out of for loop. Also you can do this job more pythonic, using one generator expression:

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

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...

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
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)

This is probably what you wanted doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM