[Python] Find and count the number of identical words from a file

Discussão em 'Python' iniciado por Stack, Abril 7, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to make a function to compare words between two files and output the number of matches.

    file1 contains:

    keywords1
    keywords2
    keywords2
    keywords3
    keywords3
    keywords4


    file2 contains (unique words):

    keywords1
    keywords2
    keywords3
    keywords4


    I want to get the number of occurrences of each word from file1 and get the following output:

    keywords1 = 1 pc
    keywords2 = 2 pc
    keywords3 = 2 pc
    keywords4 = 1 pc


    At the moment I have written this, but it seems to be not a very good approach.

    def counterDict( file_path , file_path2 ):
    source_keywords= []

    # Read and parse file keywords use regex
    with open(file_path, 'r') as file:
    source = file.read()
    for pattern in patterns:
    matches = re.findall(pattern, source)
    if matches:
    for match in matches:
    source_keywords.append(match[1])

    counter = Counter(source_keywords).most_common(500)

    # Read file with words
    with open(file_path2, 'r') as file:
    other_file = file.readlines()

    # I Want to get number of matches every words
    for word in other_file:
    for c in counter:
    if word == c[0]:
    print(f"{word} == {c[1]}")


    Upd: I solve my problem with strip line and remove new line.

    Thanks for all.

    Continue reading...

Compartilhe esta Página