-
Notifications
You must be signed in to change notification settings - Fork 1
/
csv.py
executable file
·50 lines (36 loc) · 1.03 KB
/
csv.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
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from bnf import Literal, Group, Identifier
# Separator ::= ";"
class Separator(Literal):
__token__ = ';'
__whitespaces__ = [' ', '\t']
def onMatch(self, context): pass
# EOL ::= ['\r' | '\n']+
class EOL(Identifier):
__default_regex__ = r'[\r\n]+'
__whitespaces__ = []
def onMatch(self, context): pass
# Data ::= "[^;\r\n"]*"
class Data(Identifier):
__default_regex__ = r'[^;\r\n"]*'
__whitespaces__ = []
def onMatch(self, context):
context.rows[-1].append(self.id)
# Row ::= Data [Separator Data]* EOL
class Row(Group):
__group__ = [Data, Group([Separator, Data], min=0, max=-1), EOL]
def onMatch(self, context):
context.rows.append([])
# CSV ::= [Row]+
class CSV(Group):
__group__ = Group([Row], max=-1)
csv = CSV()
print "CSV:", csv
from bnf import Context
c = Context('test.csv')
c.rows = [[]]
csv.parse(c)
print "Found rows:"
for i, row in enumerate(c.rows):
print str(i) + ": " + ''.join(("%-10s" % col) for col in row)