-
Notifications
You must be signed in to change notification settings - Fork 10
/
madlibs.py
57 lines (41 loc) · 1.4 KB
/
madlibs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
'''
Chapter 9 Reading and Writing Files
Mad Libs
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, a text file may look like this:
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.
Enter an adjective:
silly
Enter a noun:
chandelier
Enter a verb:
screamed
Enter a noun:
pickup truck
The following text file would then be created:
The silly panda walked to the chandelier and then screamed. A nearby pickup
truck was unaffected by these events.
The results should be printed to the screen and saved to a new text file.
'''
#! python3
# madlibs.py <filename> - reads <filename> and replaces any occurrences of
# 'ADJECTIVE', 'NOUN', 'ADVERB', 'VERB'.
import pyinputplus as pyip
import re
import sys
keywords = ['ADJECTIVE', 'NOUN', 'ADVERB', 'VERB']
if(len(sys.argv) == 2):
with open(sys.argv[1]) as txtfile:
txt = txtfile.read()
for keyword in keywords:
while(keyword in txt):
print(f'Found {keyword}')
replacement = pyip.inputStr(f'Enter an {keyword.lower()}: ')
txt = txt.replace(keyword, replacement, 1)
print(txt)
with open('madlibs_subs.txt', 'w') as newTxtfile:
newTxtfile.write(txt)