forked from kyclark/tiny_python_projects
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution1.py
More file actions
executable file
·56 lines (41 loc) · 1.43 KB
/
solution1.py
File metadata and controls
executable file
·56 lines (41 loc) · 1.43 KB
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
#!/usr/bin/env python3
"""Mad Libs"""
import argparse
import re
import sys
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Mad Libs',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('file',
metavar='FILE',
type=argparse.FileType('r'),
help='Input file')
parser.add_argument('-i',
'--inputs',
help='Inputs (for testing)',
metavar='str',
type=str,
nargs='*')
return parser.parse_args()
# --------------------------------------------------
def main():
"""Make a jazz noise here"""
args = get_args()
inputs = args.inputs
text = args.file.read().rstrip()
blanks = re.findall('(<([^<>]+)>)', text)
if not blanks:
print(f'"{args.file.name}" has no placeholders.', file=sys.stderr)
sys.exit(1)
tmpl = 'Give me {} {}: '
for placeholder, pos in blanks:
article = 'an' if pos.lower()[0] in 'aeiou' else 'a'
answer = inputs.pop(0) if inputs else input(tmpl.format(article, pos))
text = re.sub(placeholder, answer, text, count=1)
print(text)
# --------------------------------------------------
if __name__ == '__main__':
main()