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
