-
Notifications
You must be signed in to change notification settings - Fork 0
/
sampleproject3.py
78 lines (55 loc) · 1.95 KB
/
sampleproject3.py
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
#!/usr/bin/env python3
"""Scramble the letters of words"""
import argparse
import os
import re
import random
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Scramble the letters of words',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('text', metavar='text', help='Input text or file')
parser.add_argument('-s',
'--seed',
help='Random seed',
metavar='seed',
type=int,
default=None)
args = parser.parse_args()
if os.path.isfile(args.text):
args.text = open(args.text).read().rstrip()
return args
# --------------------------------------------------
def main():
"""Make a jazz noise here"""
args = get_args()
random.seed(args.seed)
splitter = re.compile("([a-zA-Z](?:[a-zA-Z']*[a-zA-Z])?)")
for line in args.text.splitlines():
print(''.join(map(scramble, splitter.split(line))))
# --------------------------------------------------
def scramble(word):
"""For words over 3 characters, shuffle the letters in the middle"""
if len(word) > 3 and re.match(r'\w+', word):
middle = list(word[1:-1])
random.shuffle(middle)
word = word[0] + ''.join(middle) + word[-1]
return word
# --------------------------------------------------
def test_scramble():
"""Test scramble"""
state = random.getstate()
random.seed(1)
assert scramble("a") == "a"
assert scramble("ab") == "ab"
assert scramble("abc") == "abc"
assert scramble("abcd") == "acbd"
assert scramble("abcde") == "acbde"
assert scramble("abcdef") == "aecbdf"
assert scramble("abcde'f") == "abcd'ef"
random.setstate(state)
# --------------------------------------------------
if __name__ == '__main__':
main()