Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,179 questions

56,071 answers

573 users

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 6 days ago by avibootz
...