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

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

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,596 questions

55,330 answers

573 users

How to remove duplicate words from free‑text in Python

1 Answer

0 votes
import re

def split_words(text: str) -> list:
    """
    Splits free text into words using a simple, portable regex.

    Regex explanation:
      [^A-Za-z]+   → any sequence of NON-ASCII letters

    This is not full Unicode, but it is:
      - fully supported by Python's re
      - safe and predictable
    """
    text = text.strip()

    # Split on any sequence of non-letter characters
    return re.split(r"[^A-Za-z]+", text)


def remove_duplicate_words(text: str) -> str:
    """
    Removes duplicate words while preserving:
      - original order
      - original casing of first occurrence
      - case-insensitive comparison

    Uses Python's built-in set for O(1) average lookup time.
    """
    words = split_words(text)

    seen = set()
    unique = []

    for word in words:
        if not word:
            continue

        key = word.lower()  # case-insensitive key

        if key not in seen:
            seen.add(key)
            unique.append(word)  # preserve original casing

    # Reassemble into a space-separated string
    return " ".join(unique)


# ------------------------------------------------------------
# Program entry point
# ------------------------------------------------------------
input_text = (
    "Hello, hello! This is a test. A TEST, hello universe...   "
    "UNIVERSE! Hello; ***  Is Anybody There?"
)

output = remove_duplicate_words(input_text)

print(output)


"""
run:

Hello This is a test universe Anybody There

"""

 



answered 5 days ago by avibootz
...