-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsvToHtml.py
More file actions
86 lines (71 loc) · 2.09 KB
/
csvToHtml.py
File metadata and controls
86 lines (71 loc) · 2.09 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
import sys
def main():
maxwidth = 100
print_start()
count = 0
while True:
try:
line = input()
if count == 0:
color = "lightgreen"
elif count % 2:
color = "white"
else:
color = "lightyellow"
print_line(line, color, maxwidth)
count += 1
except EOFError:
break
print_end()
def print_start():
print("<table border='1'>")
def print_line(line, color, maxwidth):
print("<tr bgcolor='{0}'>".format(color))
fields = extract_fields(line)
for field in fields:
if not field:
print("<td></td>")
else:
number = field.replace(",", "")
try:
x = float(number)
print("<td align='right'>{0:d}</td>".format(round(x)))
except ValueError:
field = field.title()
field = field.replace(" And ", " and ")
if len(field) <= maxwidth:
field = escape_html(field)
else:
field = "{0} ...".format(
escape_html(field[:maxwidth]))
print("<td>{0}</td>".format(field))
print("</tr>")
def extract_fields(line):
fields = []
field = ""
quote = None
for c in line:
if c in "\"'":
if quote is None: # start of quoted string
quote = c
elif quote == c: # end of quoted string
quote = None
else:
field += c # other quote inside quoted string
continue
if quote is None and c == ",": # end of a field
fields.append(field)
field = ""
else:
field += c # accumulating a field
if field:
fields.append(field) # adding the last field
return fields
def escape_html(text):
text = text.replace("&", "&")
text = text.replace("<", "<")
text = text.replace(">", ">")
return text
def print_end():
print("</table>")
main()