forked from widdowquinn/scripts
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtabular_to_wikitable.py
executable file
·290 lines (260 loc) · 10.6 KB
/
tabular_to_wikitable.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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
#!/usr/bin/env python
#
# tabular_to_wikitable.py
#
# Script to convert plain text tab-separated tables to MediaWiki-compatible
# wikitable markup, preserving headers and titles where possible.
#
# USAGE: tabular_to_mediawiki.py [-h] [-o OUTFILENAME] [-i INFILENAME] [-v]
# [--header HEADER] [-t TITLE] [--skip SKIP]
# [-s] [-c]
#
# optional arguments:
# -h, --help show this help message and exit
# -o OUTFILENAME, --outfile OUTFILENAME
# Output MediaWiki format table
# -i INFILENAME, --infile INFILENAME
# Input tab-separated plaintext table
# -v, --verbose Give verbose output
# --header HEADER If not passed a string of comma-separated headers,
# assumes first line of input tab-separated file is the
# header line
# -t TITLE, --title TITLE
# Set the title of the resulting MediaWiki table
# --skip SKIP Number of lines to skip at the start of the input
# file, before reading the header
# -s, --sortable Make the MediaWiki table sortable
# -c, --collapsible Make the MediaWiki table collapsible
#
# (c) The James Hutton Institute 2014
# Authors: Leighton Pritchard
#
# Contact:
# leighton.pritchard@hutton.ac.uk
#
# Leighton Pritchard,
# Information and Computing Sciences,
# James Hutton Institute,
# Errol Road,
# Invergowrie,
# Dundee,
# DD6 9LH,
# Scotland,
# UK
#
# The MIT License
#
# Copyright (c) 2010-2014 The James Hutton Institute
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
###
# IMPORTS
from argparse import ArgumentParser
import logging
import logging.handlers
import os
import sys
import traceback
###
# FUNCTIONS
# Parse command-line
def parse_cmdline(args):
""" Parse command-line arguments
"""
parser = ArgumentParser(prog="tabular_to_mediawiki.py")
parser.add_argument("-o", "--outfile", dest="outfilename",
action="store", default=None,
help="Output MediaWiki format table")
parser.add_argument("-i", "--infile", dest="infilename",
action="store", default=None,
help="Input tab-separated plaintext table")
parser.add_argument("-v", "--verbose", dest="verbose",
action="store_true",
help="Give verbose output")
parser.add_argument("--header", dest="header",
action="store", default=None,
help="If not passed a string of comma-separated " +
"headers, assumes first line of input tab-" +
"separated file is the header line")
parser.add_argument("-t", "--title", dest="title",
action="store", default=None,
help="Set the title of the resulting MediaWiki table")
parser.add_argument("--skip", dest="skip",
action="store", default=0, type=int,
help="Number of lines to skip at the start of the " +
"input file, before reading the header")
parser.add_argument("-s", "--sortable", dest="sortable",
action="store_true",
help="Make the MediaWiki table sortable")
parser.add_argument("-c", "--collapsible", dest="collapsible",
action="store_true",
help="Make the MediaWiki table collapsible")
return parser.parse_args()
# Report last exception as string
def last_exception():
""" Returns last exception as a string
"""
exc_type, exc_value, exc_traceback = sys.exc_info()
return ''.join(traceback.format_exception(exc_type, exc_value,
exc_traceback))
# Process the input stream
def process_stream(infh, outfh):
""" Processes the input stream, assuming tab-separated plaintext input,
with one row per line.
If args.header is not set, assumes that the first line contains
column headers.
If args.title is set, adds a title to the output.
If args.sortable is True, makes the table sortable.
If args.collapsible is True, makes the table collapsible.
"""
# Read in the input stream into a list of lines
try:
tbldata = list(infh.readlines())
except:
logger.error("Could not process input (exiting)")
logger.error(last_exception())
sys.exit(1)
logger.info("Read %d lines from input" % len(tbldata))
tbldata = tbldata[int(args.skip):]
logger.info("Skipping %d lines from input" % args.skip)
# How many columns are we expecting?
cols = max([len(e.split('\t')) for e in tbldata])
logger.info("Table appears to contain %d columns" % cols)
# Prepare the table style
tblclass = 'class="wikitable%s"'
classes = []
if args.sortable:
classes.append("sortable")
if args.collapsible:
classes.append("mw-collapsible")
# Apologies for the ternary operator
tblclass = tblclass % (str(' ' if len(classes) else '') +
' '.join(classes))
initstr = '{|%s' % tblclass
# Do we have a title?
if not args.title:
titlestr = "|+"
else:
try:
titlestr = "|+ %s" % args.title
except:
logger.error("Could not process the passed title: %s (exiting)" %
args.title)
logger.error(last_exception())
sys.exit(1)
# Do we have a passed header?
if args.header is not None:
try:
headerstr = process_header(cols)
except:
logger.error("Could not process the passed header string: " +
"%s (exiting)" % args.header)
logger.error(last_exception())
sys.exit(1)
else: # We'll pop the first line of the row list as a header
headerstr = '! ' + \
' !! '.join([e.strip() for e in
tbldata.pop(0).split('\t')])
# Construct table body
tblbody = '|-\n' + '\n|-\n'.join(['| ' + ' || '.join([e.strip() for e in
r.split('\t')])
for r in tbldata])
# Close table off
tblclose = "|}\n"
# Write out MediaWiki format table
outfh.write('\n'.join([initstr, titlestr, headerstr, tblbody, tblclose]))
# Process a header that was passed from the command line
def process_header(cols):
""" Splits the proposed header from the command line on commas, and checks
for the appropriate number of columns (passed as cols). If this number
is incorrect, a warning is given.
If the number of columns in the header is too few, the cells are
padded.
If the number of columens is too great, the header is accepted as-is.
"""
if not len(args.header): # empty string passed
headers = []
headercount = 0
else:
headers = str(args.header).split(',')
headercount = len(headers)
if headercount > cols:
logger.warning("Number of column headings (%d) " % headercount +
"greater than columns in data (%d)." % cols)
elif headercount < cols:
logger.warning("Number of column headings (%d) " % headercount +
"less than columns in data (%d): padding." % cols)
while headercount < cols:
headers.append("col%d" % (headercount + 1))
headercount += 1
headerstr = '! ' + ' !! '.join(headers)
return headerstr
###
# SCRIPT
if __name__ == '__main__':
# Parse command-line
args = parse_cmdline(sys.argv)
# We set up logging, and modify loglevel according to whether we need
# verbosity or not
logger = logging.getLogger('tabular_to_mediawiki.py')
logger.setLevel(logging.DEBUG)
err_handler = logging.StreamHandler(sys.stderr)
err_formatter = logging.Formatter('%(levelname)s: %(message)s')
err_handler.setFormatter(err_formatter)
if args.verbose:
err_handler.setLevel(logging.INFO)
else:
err_handler.setLevel(logging.WARNING)
logger.addHandler(err_handler)
# Report arguments, if verbose
logger.info(args)
# Do we have an input file? No? Then use stdin
if args.infilename is None:
infhandle = sys.stdin
logger.info("Using stdin for input")
else:
logger.info("Using %s for input" % args.infilename)
try:
infhandle = open(args.infilename, 'rU')
except:
logger.error("Could not open input file: %s (exiting)" %
args.infilename)
logger.error(''.join(
traceback.format_exception(sys.last_type,
sys.last_value,
sys.last_traceback)))
sys.exit(1)
# Do we have an output file? No? Then use stdout
if args.outfilename is None:
outfhandle = sys.stdout
logger.info("Using stdout for output")
else:
logger.info("Using %s for output" % args.outfilename)
try:
outfhandle = open(args.outfilename, 'w')
except:
logger.error("Could not open output file: %s (exiting)" %
args.outfilename)
logger.error(''.join(
traceback.format_exception(sys.last_type,
sys.last_value,
sys.last_traceback)))
sys.exit(1)
# Process input stream
process_stream(infhandle, outfhandle)