forked from kyclark/tiny_python_projects
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution2_no_regex.py
More file actions
executable file
·81 lines (60 loc) · 2.17 KB
/
solution2_no_regex.py
File metadata and controls
executable file
·81 lines (60 loc) · 2.17 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#!/usr/bin/env python3
"""Mad Libs"""
import argparse
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='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()
had_placeholders = False
tmpl = 'Give me {} {}: '
while True:
brackets = find_brackets(text)
if not brackets:
break
start, stop = brackets
placeholder = text[start:stop + 1]
pos = placeholder[1:-1]
article = 'an' if pos.lower()[0] in 'aeiou' else 'a'
answer = inputs.pop(0) if inputs else input(tmpl.format(article, pos))
text = text[0:start] + answer + text[stop + 1:]
had_placeholders = True
if had_placeholders:
print(text)
else:
sys.exit(f'"{args.file.name}" has no placeholders.')
# --------------------------------------------------
def find_brackets(text):
"""Find angle brackets"""
start = text.index('<') if '<' in text else -1
stop = text.index('>') if start >= 0 and '>' in text[start + 2:] else -1
return (start, stop) if start >= 0 and stop >= 0 else None
# --------------------------------------------------
def test_find_brackets():
"""Test for finding angle brackets"""
assert find_brackets('') is None
assert find_brackets('<>') is None
assert find_brackets('<x>') == (0, 2)
assert find_brackets('foo <bar> baz') == (4, 8)
# --------------------------------------------------
if __name__ == '__main__':
main()