Web M&M
https://mam.matfyz.cz
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
82 lines
2.3 KiB
82 lines
2.3 KiB
10 years ago
|
# -*- coding: utf-8 -*-
|
||
|
|
||
10 years ago
|
try:
|
||
|
from django.http import HttpResponse
|
||
|
from django.utils.encoding import force_text
|
||
|
except:
|
||
|
force_text = str
|
||
|
|
||
|
|
||
10 years ago
|
class OvvpFile(object):
|
||
|
def __init__(self):
|
||
10 years ago
|
# { header: value, ... }
|
||
10 years ago
|
self.headers = {}
|
||
10 years ago
|
# [ 'column-name', ... ]
|
||
10 years ago
|
self.columns = []
|
||
10 years ago
|
# [ { column: value, ...}, ...]
|
||
10 years ago
|
self.rows = []
|
||
|
|
||
|
def to_lines(self):
|
||
|
# header
|
||
|
for hk in sorted(self.headers.keys()):
|
||
|
yield '%s\t%s\n' % (hk, self.headers[hk])
|
||
|
yield '\n'
|
||
|
# columns
|
||
|
yield '\t'.join([c for c in self.columns]) + '\n'
|
||
|
# rows
|
||
|
for r in self.rows:
|
||
10 years ago
|
yield '\t'.join([force_text(r[c]) for c in self.columns]) + '\n'
|
||
10 years ago
|
|
||
|
def to_string(self):
|
||
|
return ''.join(self.to_lines())
|
||
|
|
||
10 years ago
|
def to_HttpResponse(self):
|
||
|
return HttpResponse(self.to_string(), content_type='text/plain; charset=utf-8')
|
||
|
|
||
10 years ago
|
def parse_from(self, source, with_headers=True):
|
||
10 years ago
|
"Parse data from file, string or line iterator, overwriting self"
|
||
|
if isinstance(source, str) or isinstance(source, unicode):
|
||
|
return self.parse_from(source.split('\n'))
|
||
|
|
||
|
it = iter(source)
|
||
|
|
||
|
# header
|
||
|
self.headers = {}
|
||
10 years ago
|
if with_headers:
|
||
|
for r in it:
|
||
|
if isinstance(r, str):
|
||
|
r = r.decode('utf8')
|
||
|
assert isinstance(r, unicode)
|
||
|
r = r.rstrip('\n')
|
||
|
if r == u"":
|
||
|
break
|
||
|
k, v = r.split(u'\t', 1)
|
||
|
self.headers[k] = v
|
||
10 years ago
|
|
||
|
# columns
|
||
|
r = it.next()
|
||
10 years ago
|
if isinstance(r, str):
|
||
|
r = r.decode('utf8')
|
||
|
self.columns = [cn.strip() for cn in r.split(u'\t') if cn.strip() != ""]
|
||
10 years ago
|
|
||
|
# rows
|
||
|
self.rows = []
|
||
|
for r in it:
|
||
10 years ago
|
if isinstance(r, str):
|
||
|
r = r.decode('utf8')
|
||
|
r = r.rstrip('\n')
|
||
10 years ago
|
if not r:
|
||
|
break
|
||
|
rtup = r.split(u'\t')
|
||
|
rdict = {}
|
||
|
for ci in range(len(self.columns)):
|
||
|
rdict[self.columns[ci]] = rtup[ci]
|
||
|
self.rows.append(rdict)
|
||
|
|
||
|
|
||
|
|
||
10 years ago
|
def parse(source, with_headers=True):
|
||
10 years ago
|
o = OvvpFile()
|
||
10 years ago
|
o.parse_from(source, with_headers=with_headers)
|
||
10 years ago
|
return o
|