Skip to content

Instantly share code, notes, and snippets.

@ubnt-intrepid
Last active August 29, 2015 14:03
Show Gist options
  • Save ubnt-intrepid/3ab2889227725c6e8cf0 to your computer and use it in GitHub Desktop.
Save ubnt-intrepid/3ab2889227725c6e8cf0 to your computer and use it in GitHub Desktop.
CSVを読み込んでTeXのtabular環境に出力するPythonスクリプト
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
CSVを読み込んでTeXのtabular環境に出力する
"""
import sys
import csv
if len(sys.argv) < 2:
print('Usage: {0} input-file [output-file]'.format(sys.argv[0]), file=sys.stderr)
sys.exit(1)
input_file = sys.argv[1]
output_file = sys.argv[2] if len(sys.argv) > 2 else None
with open(input_file, mode='r', encoding='utf-8') as f_in:
reader = csv.reader(f_in, delimiter=',')
records = [ fields for fields in reader ]
# 各レコードのフィールド数を統一させる
max_len = max(len(fields) for fields in records)
for fields in records:
cur_len = len(fields)
if cur_len < max_len:
fields.extend('' for i in range(max_len - cur_len))
bodies = map( lambda seq: ' & '.join(seq) + r' \\', records )
strs = \
r"""
\begin{{tabular}}{{{columns}}}
\hline
{body}
\hline
\end{{tabular}}
""".format( columns = '|' + '|'.join('c' for i in range(max_len)) + '|',
body = '\n'.join(bodies)
)
f_out = open(output_file, mode='w', encoding='utf-8') if output_file else sys.stdout
print(strs, file=f_out)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment