Skip to content

Commit e6206ff

Browse files
committed
Problem 17 solution
1 parent 47f1bb3 commit e6206ff

File tree

2 files changed

+84
-19
lines changed

2 files changed

+84
-19
lines changed

17_mad_libs/mad.py

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Author : Luke McGuire <[email protected]>
4+
Date : 2024-07-01
5+
Purpose: Mad Libs
6+
"""
7+
8+
import argparse
9+
import re
10+
import sys
11+
12+
13+
# --------------------------------------------------
14+
def get_args():
15+
"""Get command-line arguments"""
16+
17+
parser = argparse.ArgumentParser(
18+
description="Mad Libs", formatter_class=argparse.ArgumentDefaultsHelpFormatter
19+
)
20+
21+
parser.add_argument(
22+
"-i",
23+
"--inputs",
24+
help="A named string argument",
25+
metavar="str",
26+
type=str,
27+
nargs="*",
28+
)
29+
30+
parser.add_argument(
31+
"file", metavar="FILE", help="Input file", type=argparse.FileType("rt")
32+
)
33+
34+
return parser.parse_args()
35+
36+
37+
# --------------------------------------------------
38+
def main():
39+
"""Make a jazz noise here"""
40+
41+
args = get_args()
42+
43+
text = args.file.read().rstrip()
44+
45+
placeholders = re.findall("(<([^<>]+?)>)", text)
46+
if not placeholders:
47+
print(f'"{args.file.name}" has no placeholders.', file=sys.stderr)
48+
sys.exit(1)
49+
50+
inputs = iter(args.inputs)
51+
52+
template = "Give me {} {}: "
53+
for placeholder, word in placeholders:
54+
article: str = "an" if word[0].lower() in "aeiou" else "a"
55+
answer = next(inputs) if inputs else input(template.format(article, word))
56+
text = re.sub(placeholder, answer, text, count=1)
57+
58+
print(text)
59+
60+
61+
# --------------------------------------------------
62+
if __name__ == "__main__":
63+
main()

17_mad_libs/test.py

+21-19
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,11 @@
77
import string
88
from subprocess import getstatusoutput
99

10-
prg = './mad.py'
11-
no_blanks = 'inputs/no_blanks.txt'
12-
fox = 'inputs/fox.txt'
13-
hlp = 'inputs/help.txt'
14-
verona = 'inputs/romeo_juliet.txt'
10+
prg = "./mad.py"
11+
no_blanks = "inputs/no_blanks.txt"
12+
fox = "inputs/fox.txt"
13+
hlp = "inputs/help.txt"
14+
verona = "inputs/romeo_juliet.txt"
1515

1616

1717
# --------------------------------------------------
@@ -25,18 +25,18 @@ def test_exists():
2525
def test_usage():
2626
"""usage"""
2727

28-
for flag in ['-h', '--help']:
29-
rv, out = getstatusoutput(f'{prg} {flag}')
28+
for flag in ["-h", "--help"]:
29+
rv, out = getstatusoutput(f"python {prg} {flag}")
3030
assert rv == 0
31-
assert out.lower().startswith('usage')
31+
assert out.lower().startswith("usage")
3232

3333

3434
# --------------------------------------------------
3535
def test_bad_file():
3636
"""Test bad input file"""
3737

3838
bad = random_string()
39-
rv, out = getstatusoutput(f'{prg} {bad}')
39+
rv, out = getstatusoutput(f"python {prg} {bad}")
4040
assert rv != 0
4141
assert re.search(f"No such file or directory: '{bad}'", out)
4242

@@ -45,7 +45,7 @@ def test_bad_file():
4545
def test_no_blanks():
4646
"""Test no blanks"""
4747

48-
rv, out = getstatusoutput(f'{prg} {no_blanks}')
48+
rv, out = getstatusoutput(f"python {prg} {no_blanks}")
4949
assert rv != 0
5050
assert out == f'"{no_blanks}" has no placeholders.'
5151

@@ -54,10 +54,10 @@ def test_no_blanks():
5454
def test_fox():
5555
"""test fox"""
5656

57-
args = f'{fox} -i surly car under bicycle'
58-
rv, out = getstatusoutput(f'{prg} {args}')
57+
args = f"{fox} -i surly car under bicycle"
58+
rv, out = getstatusoutput(f"python {prg} {args}")
5959
assert rv == 0
60-
assert out.strip() == 'The quick surly car jumps under the lazy bicycle.'
60+
assert out.strip() == "The quick surly car jumps under the lazy bicycle."
6161

6262

6363
# --------------------------------------------------
@@ -71,8 +71,8 @@ def test_help():
7171
Arriba!
7272
""".strip()
7373

74-
args = f'{hlp} -i Hey tacos Oi salsa Hola queso Arriba'
75-
rv, out = getstatusoutput(f'{prg} {args}')
74+
args = f"{hlp} -i Hey tacos Oi salsa Hola queso Arriba"
75+
rv, out = getstatusoutput(f"python {prg} {args}")
7676
assert rv == 0
7777
assert out.strip() == expected.strip()
7878

@@ -98,9 +98,11 @@ def test_verona():
9898
What here shall hammer, our toil shall strive to mend.
9999
""".strip()
100100

101-
args = (f'{verona} --inputs cars Detroit oil pistons '
102-
'"stick shift" furious accelerate 42 foot hammer')
103-
rv, out = getstatusoutput(f'{prg} {args}')
101+
args = (
102+
f"{verona} --inputs cars Detroit oil pistons "
103+
'"stick shift" furious accelerate 42 foot hammer'
104+
)
105+
rv, out = getstatusoutput(f"python {prg} {args}")
104106
assert rv == 0
105107
assert out.strip() == expected.strip()
106108

@@ -110,4 +112,4 @@ def random_string():
110112
"""generate a random string"""
111113

112114
k = random.randint(5, 10)
113-
return ''.join(random.choices(string.ascii_letters + string.digits, k=k))
115+
return "".join(random.choices(string.ascii_letters + string.digits, k=k))

0 commit comments

Comments
 (0)