forked from kyclark/tiny_python_projects
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution1_regex.py
More file actions
executable file
·55 lines (40 loc) · 1.4 KB
/
solution1_regex.py
File metadata and controls
executable file
·55 lines (40 loc) · 1.4 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
#!/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('rt'),
help='Input file')
parser.add_argument('-i',
'--inputs',
help='Inputs (for testing)',
metavar='input',
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:
sys.exit(f'"{args.file.name}" has no placeholders.')
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()