Home > OS >  Checking # of times word occurs in text file (Python)
Checking # of times word occurs in text file (Python)

Time:03-27

Im working in python trying to find the # of times an input is found inside of a text file, but the output always displays the letter count of the text file in place of how many times a word occurs in the file. I am unsure as to what would cause it to output the letter count instead.

def occurrenceChecker(query):
    wordInFile = 0 
    file = open("C:\Users\Noah\Desktop\1000words.txt") 
    documentText = file.read

    for query in documentText():
        wordInFile  =1
    
    if wordInFile == 0:
        print("Your argument occurred "   str(wordInFile)   " times, none.")
    if wordInFile >= 1 and wordInFile <= 5:
        print("Your argument occurred "   str(wordInFile)   " times, low.")
    if wordInFile >= 6 and wordInFile <= 10:
        print("Your argument occurred "   str(wordInFile)   " times, medium.")
    if wordInFile >=11:
        print("Your argument occurred "   str(wordInFile)   " times, high.")

Output:

Please enter an argument that you are searching for in the file: stuck
Your argument occurred 4875 times, high.
Your argument occurred 4875 times, high.

CodePudding user response:

You are calling a function when you don't want to be and not calling a function when you do want to be.

Change for query in documentText(): to for query in document_text:

Change document_text = file.read to document_text = file.read()

def occurrenceChecker(query):
    word_in_file = 0 
    file = open("C:\Users\Noah\Desktop\1000words.txt") 
    document_text = file.read()

    for query in document_text:
        word_in_file  =1
    
    if word_in_file == 0:
        print("Your argument occurred "   str(word_in_file)   " times, none.")
    if 1 <= word_in_file <= 5:
        print("Your argument occurred "   str(word_in_file)   " times, low.")
    if 6 <= word_in_file <= 10:
        print("Your argument occurred "   str(word_in_file)   " times, medium.")
    if word_in_file>=11:
        print("Your argument occurred "   str(word_in_file)   " times, high.")

Now that you have that, we now need to address the incrementing issue. Instead of

for query in document_text:
        word_in_file  =1

You actually want to do something like this:

occurrences = document_text.count(query)

And then of course you should have a main() and call your function in said main()

def main():
    occurrenceChecker(input())

if __name__ == "__main__":
    main()

Source: https://pythonexamples.org/python-count-occurrences-of-word-in-text-file/

  • Related