TSV to HTML

Tim Chase python.list at tim.thechases.com
Wed May 31 14:47:17 EDT 2006


 > I was wondering if anyone here on the group could point me
 > in a direction that would expllaing how to use python to
 > convert a tsv file to html.  I have been searching for a
 > resource but have only seen information on dealing with
 > converting csv to tsv.  Specifically I want to take the
 > values and insert them into an html table.
 >
 > I have been trying to figure it out myself, and in
 > essence, this is what I have come up with.  Am I on the
 > right track? I really have the feeling that I am
 > re-inventing the wheel here.
 >
 > 1) in the code define a css
 > 2) use a regex to extract the info between tabs
 > 3) wrap the values in the appropriate tags and insert into
 > table.
 > 4) write the .html file

Sounds like you just want to do something like

	print "<table>"
	for line in file("in.tsv"):
		print "<tr>"
		items = line.split("\t")
		for item in items:
			print "<td>%s</td>" % item
		print "</tr>"
	print "</table>"

It gets a little more complex if you need to clean each item
for HTML entities/scripts/etc...but that's usually just a
function that you'd wrap around the item:

			print "<td>%s</td>" % escapeEntity(item)

using whatever "escapeEntity" function you have on hand.
E.g.

from xml.sax.saxutils import escape
:
:
			print "<td>%s</td>" % escape(item)

It doesn't gracefully attempt to define headers using
<thead>, <tbody>, and <th> sorts of rows, but a little
toying should solve that.

-tim








More information about the Python-list mailing list