Skip to content

Instantly share code, notes, and snippets.

@AdoHaha
Created January 4, 2016 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AdoHaha/89e0fa90af00e9a883f6 to your computer and use it in GitHub Desktop.
Save AdoHaha/89e0fa90af00e9a883f6 to your computer and use it in GitHub Desktop.
''' gist below can accept a csv list with unicode coding, for example list of names from around the world as in example'''
import csv,codecs,cStringIO
import jinja2
''' copied from StackExchange'''
class UTF8Recoder:
def __init__(self, f, encoding):
self.reader = codecs.getreader(encoding)(f)
def __iter__(self):
return self
def next(self):
return self.reader.next().encode("utf-8")
class UnicodeReader:
def __init__(self, f, dialect=csv.excel, encoding="utf-8-sig", **kwds):
f = UTF8Recoder(f, encoding)
self.reader = csv.reader(f, dialect=dialect, **kwds)
def next(self):
'''next() -> unicode
This function reads and returns the next line as a Unicode string.
'''
row = self.reader.next()
return [unicode(s, "utf-8") for s in row]
def __iter__(self):
return self
class UnicodeWriter:
def __init__(self, f, dialect=csv.excel, encoding="utf-8-sig", **kwds):
self.queue = cStringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, row):
'''writerow(unicode) -> None
This function takes a Unicode string and encodes it to the output.
'''
self.writer.writerow([s.encode("utf-8") for s in row])
data = self.queue.getvalue()
data = data.decode("utf-8")
data = self.encoder.encode(data)
self.stream.write(data)
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
''' meat of the conversion'''
raw_template=r'''<ul>
{% for person in people %}
<li style="margin-left: 20px;">{{person[1]}} {{person[0]}}</li>
{% endfor %}
</ul>'''
list_template=jinja2.Template(raw_template)
with open('./list_of_people.csv') as list_of_people:
people_reader=UnicodeReader(list_of_people,delimiter=',') #it is a comma separated file
print list_template.render(people=list(people_reader)) # prints the html list in this case of people
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment