[Python] How to count full-word phrase occurrences in Python (with apostrophes and hyphens)

Discussão em 'Python' iniciado por Stack, Julho 15, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to count how many times a full-word phrase appears in a text in Python, case-insensitively.

    ⚠️ The requirements are:

    • Only exact phrase matches (in order, no fuzzy matching)
    • A "word" may contain apostrophes (') and hyphens (-) inside it, such as "don't" or "skin-care"
    • The phrase must match whole words only, not substrings inside other words

    For example:

    • "don't" should match "Don't be late!"
    • "maley" should not match "O'maley"
    • "skin-care monopoly" should match "a skin-care monopoly"
    • "care" should not match "skin-care"

    Here is the base function:

    def count_occurrences_in_text(word, text):
    """
    Count full-word phrase occurrences in the text, case-insensitive.
    Words may contain apostrophes and hyphens inside words (like don't, skin-care),
    but matches must be exact and not part of larger words.
    """
    # TODO: Implement robust logic
    pass


    assert count_occurrences_in_text("don't", "Don't be late!") == 1
    assert count_occurrences_in_text("maley", "John O'maley is my friend") == 0
    assert count_occurrences_in_text("skin-care", "Enable a skin-care monopoly") == 1
    assert count_occurrences_in_text("care", "Enable a skin-care monopoly") == 0
    assert count_occurrences_in_text("Linguist", "'''Linguist Specialist Found Dead on Floor'''") == 1
    assert count_occurrences_in_text("reflexion mirror", 'I live at the “Reflexion Mirror” resort') == 1
    assert count_occurrences_in_text("reflexion mirror", '...Fun-Plex «Reflexion Mirror»...') == 1
    assert count_occurrences_in_text("legitimate their", "This is legitimate: their employees...") == 0
    assert count_occurrences_in_text("get back to me", "When you know: get back to me.") == 1





    I try a lot of things but nothing conclusive.

    `text.lower().count(word.lower())`
    Using regex with \b

    Continue reading...

Compartilhe esta Página