Introduction To Programming - Exercise Sheet 7 - Solution Introduction To Programming, ITU (Autumn 2022)
Introduction To Programming - Exercise Sheet 7 - Solution Introduction To Programming, ITU (Autumn 2022)
57
Save the file as learning_python.txt in the same directory as the one where you store
your Python programs.
Write a program that reads the file and prints what you wrote three times. Print the contents
once by reading in the entire file, once by looping over the file object, and once by storing
the lines in a list and then working with them outside the with block (as suggested in the
preparation material).
Solution:
filename = 'learning_python.txt'
Write a while loop that prompts users for their name. When they enter their name, print a
greeting to the screen and add a line recording their visit in a file called guest_book.txt .
Make sure each entry appears on a new line in the file by opening it in a text editor.
Solution:
print
print("Please enter 'quit' when finished")
with open('guest_book.txt', 'a', encoding=
="utf8") as f:
while True:
name = input("Please write your name: ")
if name == 'quit':
break
f.write(name + "\n")
print
print(f"Greetings {name}, you are now in the guest book")
Write a program that tries to read these files and print the contents of the file to the screen.
Wrap your code in a try-except block to catch the FileNotFound error, and print a
friendly message if a file is missing. Move one of the files to a different location on your
system, and make sure the code in the except block is executed properly.
Solution:
https://github.itu.dk/pages/ip/2022/exercises/exercise_07_solutions/ Page 2 of 4
Introduction to programming - Exercise Sheet 7 - Solution · Introduction to Programming, ITU (Autumn 2022) 08/11/2022, 17.57
content of the file. Next, write a program that prints the item that has been sold most
frequently.
Suggested Approach: Read the file line-by-line and count frequencies using a dictionary, as
earlier in class. Find the item with maximum frequency and return it.
Suggested solution:
sold = {}
with open('sales.txt') as f:
for line in f:
sold.setdefault(line, 0)
sold[line] += 1
print
print(max(sold, key==sold.get))
Task 5 (MadLibs)
Create a Mad Libs program that reads in text files and lets the user add their own text
anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file. For
example, the text file madlibs1.txt has the following content:
The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was
unaffected by these events.
The program would find these occurrences and prompt the user to replace them, like so:
Enter an adjective:
silly
Enter a noun:
chandelier
Enter a verb:
screamed
Enter a noun:
pickup truck
The silly panda walked to the chandelier and then screamed. A nearby pickup
truck was unaffected by these events.
https://github.itu.dk/pages/ip/2022/exercises/exercise_07_solutions/ Page 3 of 4
Introduction to programming - Exercise Sheet 7 - Solution · Introduction to Programming, ITU (Autumn 2022) 08/11/2022, 17.57
def read(filename):
with open(filename) as file:
words = file.read().split()
for i in range(len(words)):
if words[i].startswith(('ADJECTIVE')):
words[i] = input('Enter an adjective: ')
if words[i].startswith(('NOUN')):
words[i] = input('Enter a noun: ')
if words[i].startswith(('ADVERB')):
words[i] = input('Enter an adverb: ')
if words[i].startswith(('VERB')):
words[i] = input('Enter a verb: ')
return ' '.join(words)
print(read('madlibs1.txt'))
import re
def read(filename):
regex = re.compile(r"ADJECTIVE|VERB|ADVERB|NOUN")
with open(filename) as file:
words = file.read().split()
for i in range(len(words)):
if regex.match(words[i]):
match = regex.search(words[i]) # create regex object on word
if match.group() in ('ADJECTIVE', 'ADVERB'):
new = input(f'Enter an {match.group().lower()}: ')
else:
new = input(f'Enter a {match.group().lower()}: ')
words[i] = regex.sub(new, words[i], 1)
return ' '.join(words)
print(read('madlibs1.txt'))
https://github.itu.dk/pages/ip/2022/exercises/exercise_07_solutions/ Page 4 of 4