A data structure is an organized way to store information in a particular format. Choosing one helps a program access, modify, and work with data appropriately. section 1.2 section 29.3
Use data structures to make information easier for a program to handle:
- Choose among learned data types before coding, and select the simplest suitable option when several could work. section 29.3
- Put related data into a container when modifying its contents is more useful than creating a replacement container. section 24.0
- Break a large string into a list when separate elements, such as individual words, are easier to process. section 29.3
Turning document text into a list
A document begins as one large string, but a word-comparison program needs its words separately. Clean newline and punctuation characters, split the remaining text at spaces, and return the resulting list. Testing the function first on a short file makes mistakes easier to find. section 29.3
Listing 29.2. Finding words from a string
import string #1
def find_words(text):
"""
text: string
returns: list of words from input text
"""
text = text.replace("\n", " ") #2
for char in string.punctuation: #3
text = text.replace(char, "") #4
words = text.split(" ") #5
return words #6
words = find_words(text) #7
Inspect the complete find_words function, including cleanup, punctuation removal, splitting, and returning the list. section 29.3









