-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand_parser.py
More file actions
executable file
·115 lines (79 loc) · 2.43 KB
/
Copy pathcommand_parser.py
File metadata and controls
executable file
·115 lines (79 loc) · 2.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
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import argparse
import os
import string
import sys
from itertools import chain
def clean_words(readlines):
'''
list -> list of str
Remove the punctuation from input list: readlines.
'''
cleaned = []
for line in readlines:
for word in line.split():
cleaned.append((word.strip(string.punctuation) + ' '))
return cleaned
class ParserResult:
"""docstring for ClassName"""
def __init__(self, input_file):
self._input_file = input_file
def output_file(self, filename, input_file):
'''
str, list -> None
Outputs a file with given content and the name given if
the file does not exists, otherwise prints an error message.
'''
if os.path.exists(filename):
sys.stdout.write('The file already exists, cannot be created!\n')
sys.exit()
else:
_output_file = file('{}'.format(filename), 'wt')
[_output_file.write(i) for i in input_file]
_output_file.close()
def sort_file(self):
'''
file -> list
Read the input file in a list and return the sorted version of it.
'''
try:
# added method for testcase, when a file-like object it's used instead
# of a real file.
return sorted(clean_words(self._input_file),
key=lambda s:s.lower())
except AttributeError:
with self._input_file as f:
return sorted(clean_words(f.readlines()),
key=lambda s: s.lower())
def sort_lines(self):
pass
def sort_lines_and_words(self):
pass
def main():
parser = argparse.ArgumentParser(description='''Takes in
as an argument the name of a file.''')
parser.add_argument('sort', type=argparse.FileType('r'),
help='''Output the lines from file
in sorted alphabetical order.''')
parser.add_argument('-r', '--reversed', action='store_true', help='''Output the
lines in reversed order.''')
parser.add_argument('-o', '--output', type=str, help='''Output
the result in a new file''')
args = parser.parse_args()
results = ParserResult(args.sort)
if args.reversed:
if args.output:
results.output_file(args.output, reversed(results.sort_file()))
sys.stdout.write('%s is now reversed.\n' % args.output)
else:
[sys.stdout.write(item) for item in reversed(results.sort_file())]
elif args.output:
results.output_file(args.output, results.sort_file())
else:
output = chain(results.sort_file())
try:
while True:
sys.stdout.write(output.next())
except StopIteration:
sys.stdout.write('\n')
if __name__ == '__main__':
main()