[Python] Search text file and count occurrences of a specified string

Discussão em 'Python' iniciado por Stack, Fevereiro 2, 2025.

  1. Stack

    Stack Membro Participativo

    I am attempting to use python to search a text file and count the number of times a user defined word appears. But when I run my code below, instead of getting a sum of the number of times that unique word appears in the file, I am getting a count for the number lines within that file contain that word.

    Example: the word 'bob' exists 56 times in the text file, appearing in 19 of the total 63 lines of text. When I run my code the console prints '19'.

    I am guessing I need to do something different with my split method?

    user_search_value = input("Enter the value or string to search for: ")

    count = 0

    with open(file.txt, 'r') as f:
    for word in f.readlines():
    words = word.lower().split()
    if user_search_value in words:
    count += 1
    print(count)

    Continue reading...

Compartilhe esta Página