liveBook · Manning

Clean_word

As explained in Learn AI-Assisted Python Programming, Second Edition

clean_word is a book-specific Python function that removes punctuation surrounding a word and converts the word to lowercase while preserving punctuation within the word.

clean_word prepares a word for text analysis by converting letters to lowercase and removing punctuation from both ends. It preserves punctuation inside the word, so card-board remains unchanged internally. section 11.5.1

The function supports analysis by:

  • Removing surrounding punctuation so words such as pearl., pearl!!, and (pearl) can be counted by their letters. section 11.3.1
  • Converting Pearl and PEARL to the same lowercase form for word comparisons. section 11.3.1
  • Returning an empty string for punctuation-only input, allowing analysis functions to exclude it as a nonword. section 11.3.1

Cleaning words for analysis

clean_word('Pearl!') returns 'pearl', while clean_word('card-board') returns 'card-board'. The implementation lowercases the input and then strips punctuation from its ends. section 11.5.1

Listing 11.1 Clean words for analysis
def clean_word(word):
    '''
    word is a string.

    Return a version of word in which all letters have been
    converted to lowercase, and punctuation characters have been
    stripped from both ends. Inner punctuation is left untouched.
    
    >>> clean_word('Pearl!')
    'pearl'
    >>> clean_word('card-board')
    'card-board'
    '''
    word = word.lower()                #1
    word = word.strip(string.punctuation)   #2
    return word

Inspect the complete doctest-backed implementation and its examples. section 11.5.1

How Learn AI-Assisted Python Programming, Second Edition covers it

How deep it goes
Defines a two-step implementation using lower() and strip(string.punctuation), with doctests for edge behavior.
Examples
Uses Pearl!, card-board, punctuation-only input, and case variants such as Pearl and PEARL.
What you can do after
Build it from scratch as a reusable Python helper for normalizing words before text analysis.
How it connects
Connects to average_word_length, different_to_total, string punctuation, and function decomposition.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn AI-Assisted Python Programming, Second Edition. The section links point to the parts of the book it draws on.