-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv_parser.py
243 lines (212 loc) · 8.52 KB
/
csv_parser.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
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
import csv
import fileinput
import sys
from tabulate import tabulate
debug = True
def main():
try:
if len(sys.argv) == 1:
#filename = "test.csv"
filename = input("CSV file name = ")
elif len(sys.argv) == 2:
filename = str(sys.argv[1])
elif len(sys.argv) > 2:
print ("Specify just one CSV file as command line argument")
return
### MENU
printMenu()
while(True):
menu = input("\nChoose operation number: ")
if menu == '0':
### necessary if delimiter is ";" instead of ','
searchExp = ";"
replaceExp = ","
replaceAll(filename,searchExp,replaceExp)
elif menu == '1':
### print column titles
columnList = getColumnTitles(filename)
print("\nColumn list:")
i=0
for col in columnList:
i += 1
print("col%03d: " % i, col)
elif menu == '2':
colIndex = input('column index list (from 1, separated by comma): ')
keywords = input('keyword(s): ')
if colIndex == '':
### find rows by keyword list:
findRowByKeywordList(filename, keywords)
else:
### find rows by column index and keyword list:
findRowByColumnAndKeywordList(filename, colIndex, keywords)
elif menu == '3':
colIndex = input('column index list (from 1, separated by comma): ')
keywords = input('keyword(s): ')
if colIndex == '':
### find rows by keyword list:
findRowByKeywordList_subs(filename, keywords)
else:
### find rows by column index and keyword list:
findRowByColumnAndKeywordList_subs(filename, colIndex, keywords)
elif menu == '4':
### print a table from the CSV file
printTable(filename)
elif menu == '5':
print ("Not yet implemented")
elif menu == '6':
print ("Not yet implemented")
elif menu == '7':
print ("Not yet implemented")
elif menu == '8':
print ("Not yet implemented")
elif menu == '9':
print ("Not yet implemented")
elif menu == 'm':
printMenu()
else:
print ("Unknown choice")
return
except KeyboardInterrupt:
### to intercept CRTL+C interrupt
print ("\nQuitting...")
except Exception as e:
print("Exception: " + repr(e))
def getColumnTitles(filename):
with open(filename) as csvfile:
reader = csv.DictReader(csvfile)
firstRow = next(reader)
columnList = firstRow.keys()
return columnList
def findRowByKeywordList(filename, keywords):
with open(filename) as csvfile:
reader = csv.DictReader(csvfile)
keywordList = keywords.split(",")
keywordListUp = [kw.strip().upper() for kw in keywordList if kw is not None] #list uppercase
print ("searching for: ", keywordListUp)
firstRow = True
for row in reader:
if firstRow:
firstRow = False
columnTitles = row.keys()
print (columnTitles)
row_keys = row.keys()
row_keys = [k.strip().upper() for k in row_keys if k is not None]
row_values = row.values()
row_values = [v.strip().upper() for v in row_values if v is not None]
for kw in keywordListUp:
if kw in row_values:
print (row.values())
def findRowByColumnAndKeywordList(filename, colIndexList, keywords):
colIndexList = colIndexList.split(",")
colIndexList = [int(c)-1 for c in colIndexList if c is not None]
with open(filename) as csvfile:
reader = csv.DictReader(csvfile)
keywordList = keywords.split(",")
keywordListUp = [kw.strip().upper() for kw in keywordList if kw is not None] #list uppercase
print ("searching for: ", keywordListUp)
firstRow = True
for row in reader:
if firstRow:
firstRow = False
columnTitles = row.keys()
if max(colIndexList) > len(columnTitles):
raise ValueError('Wrong index value specified')
print (columnTitles)
row_keys = row.keys()
row_keys = [k.strip().upper() for k in row_keys if k is not None]
row_values = row.values()
row_values = [v.strip().upper() for v in row_values if v is not None]
for kw in keywordListUp:
for colIndex in colIndexList:
if kw == row_values[colIndex]:
print (row.values())
def findRowByKeywordList_subs(filename, keywords):
with open(filename) as csvfile:
reader = csv.DictReader(csvfile)
keywordList = keywords.split(",")
keywordListUp = [kw.strip().upper() for kw in keywordList if kw is not None] #list uppercase
print ("searching for: ", keywordListUp)
firstRow = True
for row in reader:
if firstRow:
firstRow = False
columnTitles = row.keys()
print (columnTitles)
row_keys = row.keys()
row_keys = [k.strip().upper() for k in row_keys if k is not None]
row_values = row.values()
row_values = [v.strip().upper() for v in row_values if v is not None]
for kw in keywordListUp:
for v in row_values:
if kw in v:
print (row.values())
def findRowByColumnAndKeywordList_subs(filename, colIndexList, keywords):
colIndexList = colIndexList.split(",")
colIndexList = [int(c)-1 for c in colIndexList if c is not None]
print(colIndexList)
with open(filename) as csvfile:
reader = csv.DictReader(csvfile)
keywordList = keywords.split(",")
keywordListUp = [kw.strip().upper() for kw in keywordList if kw is not None] #list uppercase
print ("searching for: ", keywordListUp)
firstRow = True
for row in reader:
if firstRow:
firstRow = False
columnTitles = row.keys()
if max(colIndexList) > len(columnTitles):
raise ValueError('Wrong index value specified')
print (columnTitles)
row_keys = row.keys()
row_keys = [k.strip().upper() for k in row_keys if k is not None]
row_values = row.values()
row_values = [v.strip().upper() for v in row_values if v is not None]
for kw in keywordListUp:
for colIndex in colIndexList:
if colIndex >= len(row_values):
break
elif kw in row_values[colIndex]:
print (row.values())
def printTable(filename):
columnTitles = getColumnTitles(filename)
with open(filename) as csvfile:
reader = csv.DictReader(csvfile)
row_list = []
for row in reader:
element_list = []
for element in row.values():
element_list.append(element)
row_list.append(element_list)
print (tabulate(row_list, headers=columnTitles))
def listToArray(inputList):
outputArray = [len(inputList)]
i = 0
for element in inputList:
outputArray.append(element)
i = i + 1
debugPrint (outputArray)
return outputArray
def replaceAll(file,searchExp,replaceExp):
for line in fileinput.input(file, inplace=1):
if searchExp in line:
line = line.replace(searchExp,replaceExp)
sys.stdout.write(line)
def printMenu():
menu = """\n**********MENU**********
1) print column titles
2) search list of keywords
3) search list of keywords considering substrings
4) print table from CSV
5)
6)
7)
8)
9)
0) replace ';' with ','
m) print menu"""
print (menu)
def debugPrint(x):
if debug:
print (x)
if __name__ == "__main__":
main()