Write a function madlibs () that takes in 4 parameters: a list of nouns, a list
ID: 3828927 • Letter: W
Question
Write a function madlibs() that takes in 4 parameters: a list of nouns, a list of verbs a list of adjectives and some text. The text will have NNN for a place to inject a random noun from the list, VVV to inject a random verb from the list and AAA to inject a random adjective from the list. The function will print the text with the values replaced. Here is some sample output. HINT: Break the text up into individual strings.
import random
def madlibs(nouns, verbs, adjectives, text):
pass
n=['dog', 'boy', 'girl', 'donkey', 'teacher', 'father','policeman','guard']
v=['ran','barfed','sang','barked','shouted','flew']
a=['angry','sad','happy','hungry','silly','stunned','drunk']
sentence='The AAA NNN VVV at the NNN'
madlibs(n,v,a,sentence)
sentence='A NNN looked at the NNN and then VVV at the AAA NNN'
madlibs(n,v,a,sentence)
Explanation / Answer
Below is the full program alongwith output. Please post comments if any explanation/help required
import random
def nth_repl(s, sub, repl):
find = s.find(sub)
i = find != -1
return s[:find]+repl+s[find + len(sub):]
return s
def madlibs(nouns, verbs, adjectives, text):
nn_cnt=text.count('NNN')
vv_cnt=text.count('VVV')
aa_cnt=text.count('AAA')
for i in range(0,nn_cnt):
nn=random.choice(nouns)
text=nth_repl(text,"NNN",nn)
for i in range(0,vv_cnt):
vv=random.choice(verbs)
text=nth_repl(text,"VVV",vv)
for i in range(0,aa_cnt):
aa=random.choice(adjectives)
text=nth_repl(text,"AAA",aa)
print text
pass
n=['dog', 'boy', 'girl', 'donkey', 'teacher', 'father','policeman','guard']
v=['ran','barfed','sang','barked','shouted','flew']
a=['angry','sad','happy','hungry','silly','stunned','drunk']
sentence='The AAA NNN VVV at the NNN'
madlibs(n,v,a,sentence)
sentence='A NNN looked at the NNN and then VVV at the AAA NNN'
madlibs(n,v,a,sentence)
o/p:
python main.py
The stunned father shouted at the girl
A girl looked at the guard and then barked at the drunk boy
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.