-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsv2tex.py
More file actions
141 lines (107 loc) · 2.89 KB
/
Copy pathcsv2tex.py
File metadata and controls
141 lines (107 loc) · 2.89 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
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
import csv
import os.path
import sys
def tex_header(header: list) -> str:
"""
This method builds a LaTeX header based on
the csv list of columns. Uses booktabs environment.
Parameters
----------
header : list
The list of column names
Return
----------
The TeX-formatted string
"""
head = ('\\begin{table}\n'
'\t\\centering\n'
'\t\\caption{\\label{My awesome label} My awesome caption}\n'
'\t\\begin{tabular}{')
for _ in header:
head += 'l'
head += '}\n\t\t'
head += '\\toprule\n\t\t'
# Column names
cnt = 1
for c in header:
if cnt < len(header):
head += f"{c} & "
cnt += 1
else:
head += f"{c} \\\\ \n"
return head + '\t\t\\midrule\n'
def tex_footer() -> str:
"""
This method builds a LaTeX table footer
Return
----------
The TeX-formatted string
"""
return ('\\bottomrule \n'
'\t\\end{tabular} \n'
'\\end{table}')
def tex_content(reader) -> str:
"""
This method builds the LaTeX body based on
the csv list of rows.
Parameters
----------
reader : csvreader
The csv reader
Return
----------
str
The TeX-formatted string
"""
content = '\t\t'
cnt = 1
for row in reader:
for elem in row:
if cnt < len(row):
content += f"{elem} & "
cnt += 1
else:
content += f"{elem} \\\\ \n \t\t"
cnt = 1
return content
def to_tex(csvfile):
"""
This method reads a csv file and writes a
LaTeX table with the content. The .tex file is
saved in the same folder of the csv file with
the same name.
Parameters
----------
csvfile : File
The csv file to convert
"""
tex_string = ''
with open(csvfile) as f:
reader = csv.reader(f)
header = next(reader)
tex_string += tex_header(header)
tex_string += tex_content(reader)
tex_string += tex_footer()
with open(f"{csvfile.replace('.csv', '')}_converted.tex", 'w') as f:
f.write(tex_string)
print('Conversion successful')
def show_help():
print('\ncsv2tex: convert your csv values in a TeX-formatted table.\n'
'-\n'
'- Usage: python csv2tex.py <path_to_csv_file>.csv\n'
'-\n'
'- If the given csv file exists, a new .tex file will be created within\n'
'- the same directory and with the same name.\n'
'-\n'
'- Stefano Demarchi')
# Main entry point
if __name__ == '__main__':
if len(sys.argv) == 2:
if sys.argv[1] == '-h':
show_help()
elif os.path.isfile(sys.argv[1]):
to_tex(sys.argv[1])
else:
print('Error: incorrect file specified')
else:
show_help()