How to find common words in two strings with Python

1 Answer

0 votes
"""
This program finds common words between two strings.

It uses:
- A normalization function to lowercase text and replace non‑letters
- Python's split() for tokenizing
- Sets for fast lookup and automatic duplicate removal
- A simple, efficient intersection operation
"""

def normalize(text: str) -> str:
    """
    Normalize a string:
    - Convert letters to lowercase
    - Replace any non-letter with a space
    This ensures consistent word comparison.
    """
    result = []
    for ch in text:
        if ch.isalpha():
            result.append(ch.lower())
        else:
            result.append(" ")
          
    return "".join(result)


def extract_words(text: str) -> set[str]:
    """
    Extract words from a string.

    This function:
    - Normalizes the input
    - Splits on whitespace
    - Filters out empty entries
    - Returns a set for fast lookup and automatic duplicate removal
    """
    normalized = normalize(text)
    parts = normalized.split()
  
    return set(parts)


def find_common_words(a: str, b: str) -> set[str]:
    """
    Find common words between two strings.

    This function:
    - Extracts words from both strings
    - Uses set intersection for efficiency
    - Returns a new set containing the common words
    """
    words_a = extract_words(a)
    words_b = extract_words(b)
  
    return words_a & words_b  # efficient intersection


def main():
    s1 = "The quick brown fox jumps over the lazy dog."
    s2 = "A lazy dog sleeps while the quick fox runs away."

    common = find_common_words(s1, s2)

    print("Common words:")
    for w in sorted(common):
        print(w)


if __name__ == "__main__":
    main()


"""
run:

Common words:
dog
fox
lazy
quick
the

"""

 



answered Sep 11 by avibootz
...