Skip to content

Instantly share code, notes, and snippets.

@spacestate1
Forked from 0ncorhynchus/csv2wikitable.py
Last active August 14, 2022 03:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spacestate1/4b270dab6d1a4788f69c1e111666d01c to your computer and use it in GitHub Desktop.
Save spacestate1/4b270dab6d1a4788f69c1e111666d01c to your computer and use it in GitHub Desktop.
convert csv to wiki table
#!/usr/bin/python
"""
Usage: python csv2wikitable.py csv_file
-----
input: csv format
output: wiki table format
"""
import sys
if __name__ == '__main__':
argvs = sys.argv
argcs = len(argvs)
if argcs != 2:
sys.stderr.write('Usage: python %s csv_file column count\n' % argvs[0])
sys.exit(1)
filename = argvs[1]
#column_count = argvs[2]
infile = open(filename, 'r')
inlines = infile.readlines()
infile.close()
for line2 in inlines:
n1 = ((line2.count(",")))
for line3 in inlines:
n2 = ((line3.count(",")))
if (n2 > n1):
n3 = n2;
outlines = []
for line in inlines:
# outlines.append(line.replace('\n','\n|-\n'))
commas_count = (line.count(","))
if commas_count <= n3:
n4 = (n3 - commas_count)
line = line.rstrip('\n')
line = line.rstrip ('\r')
line = line.replace('-',' -')
line += (',' * n4)
line += ('\n')
if line.strip():
outlines.append(line)
outlines = [lines1.replace('\n','\n|-\n') for lines1 in outlines]
outlines = [lines2.replace(",", "\n|") for lines2 in outlines]
outlines = [lines3.replace("\r", "\n|-\n|") for lines3 in outlines]
outlines = ['|'+line4 for line4 in outlines]
outfile = open('wiki_'+filename, 'w')
outfile.write('{| class = class="wikitable"\n')
outfile.writelines(outlines)
outfile.write('|}')
outfile.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment