Skip to content

Commit 1bf8fdd

Browse files
authored
Merge pull request #28 from lcongdon:mad
Mad
2 parents 0726798 + 0da73b3 commit 1bf8fdd

2 files changed

Lines changed: 54 additions & 0 deletions

File tree

‎17_mad_libs/mad.py‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Author : Lee A. Congdon <lee@lcongdon.com>
4+
Date : 2021-09-05
5+
Purpose: Tiny Python Projects Mad Libs exercise
6+
"""
7+
8+
import sys
9+
import argparse
10+
import re
11+
12+
13+
def get_args():
14+
"""Parse arguments"""
15+
16+
parser = argparse.ArgumentParser(
17+
description='Mad Libs',
18+
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
19+
20+
parser.add_argument('-i',
21+
'--inputs',
22+
nargs='+',
23+
default='',
24+
type=str,
25+
help='Input strings (for testing)',
26+
metavar='input')
27+
28+
parser.add_argument('file',
29+
help='Input file',
30+
metavar='FILE')
31+
32+
return parser.parse_args()
33+
34+
35+
def main():
36+
"""Main program"""
37+
38+
args = get_args()
39+
text = open(args.file, "r", encoding="utf-8").read().rstrip()
40+
pattern = re.compile(r'(<([^<>]+)>)')
41+
matches = re.findall(pattern, text)
42+
if not matches:
43+
sys.exit(f'"{args.file}" has no placeholders.')
44+
if not args.inputs:
45+
args.inputs = []
46+
for placeholder, name in matches:
47+
article = 'an' if name[0].lower() in 'aeiou' else 'a'
48+
args.inputs.append(input(f'Give me {article} {name}: '))
49+
for replacement in args.inputs:
50+
text = re.sub(pattern, replacement, text, count=1)
51+
print(text)
52+
53+
if __name__ == '__main__':
54+
main()

0 commit comments

Comments
 (0)