def read_poetry_form_description(poetry_forms_file):
""" (file open for reading) -> poetry pattern
Precondition: we have just read a poetry form name from poetry_forms_file.
Return the next poetry pattern from poetry_forms_file.
"""
# Create three empty lists
syllables_list = []
rhyme_list = []
pattern_list = []
# Read the first line of the pattern
line = poetry_forms_file.readline()
# Read until the end the the pattern
while line != '\n' and line != '':
# Clean the \n's
pattern_list.append(line.replace('\n', '').split(' '))
line = poetry_forms_file.readline()
# Add elements to lists
for i in pattern_list:
syllables_list.append(int(i[0]))
rhyme_list.append(i[1])
# Add two lists into a tuple
pattern = (syllables_list, rhyme_list)
return pattern
def read_poetry_form_descriptions(poetry_forms_file):
""" (file open for reading) -> dict of {str: poetry pattern}
Return a dictionary of poetry form name to poetry pattern for the
poetry forms in poetry_forms_file.
"""
# Initiate variables
forms_dict = {}
keys = []
values = []
# Get the first form
line = poetry_forms_file.readline()
# Add the name to the keys list
keys.append(line.replace('\n', ''))
# Add the variable to the values list using the previous function
values.append(read_poetry_form_description(poetry_forms_file))
while line != '':
# Check if the line is the beginning of a form
if line == '\n':
line = poetry_forms_file.readline()
keys.append(line.replace('\n', ''))
values.append(read_poetry_form_description(poetry_forms_file))
else:
line = poetry_forms_file.readline()
# Add key-value pairs to the dictionary
for i in range(len(keys)):
forms_dict[keys[i]] = values[i]
return forms_dict
So the problem occurs when I tried to test my code using the text file. It returns the following: read_poetry_form_descriptions(open('poetry_forms.txt'))
{'Limerick': ([8, 8, 5, 5, 8], ['A', 'A', 'B', 'B', 'A']), 'Rondeau': ([8, 8, 8, 8, 8, 8, 8, 8, 4, 8, 8, 8, 8, 8, 4], ['A', 'A', 'B', 'B', 'A', 'A', 'A', 'B', 'C', 'A', 'A', 'B', 'B', 'A', 'C']), 'Haiku': ([5, 7, 5], ['', '', '*'])}
Which is supposed to have another two key-value pairs. This is what's in the text file:
Haiku
5 *
7 *
5 *
Sonnet
10 A
10 B
10 A
10 B
10 C
10 D
10 C
10 D
10 E
10 F
10 E
10 F
10 G
10 G
Limerick
8 A
8 A
5 B
5 B
8 A
Quintain (English)
0 A
0 B
0 A
0 B
0 B
Rondeau
8 A
8 A
8 B
8 B
8 A
8 A
8 A
8 B
4 C
8 A
8 A
8 B
8 B
8 A
4 C