forked from pjkundert/cpppo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
readme.py
59 lines (47 loc) · 1.89 KB
/
readme.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
51
52
53
54
55
56
57
58
59
#!/usr/bin/env python
#
# readme.py: A demo of plain and composite cpppo state machinery; works under python 2 or 3
#
from __future__ import print_function
import os, sys
try:
import cpppo
except ImportError:
# Allow import of 'cpppo' when executing within 'cpppo' package directory
sys.path.insert( 0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import cpppo
# To enable logging, uncomment:
# import logging
# logging.basicConfig( **cpppo.log_cfg )
# #logging.getLogger().setLevel( logging.DEBUG )
def main():
"""The basic examples in the README"""
# Basic DFA that accepts ab+
E = cpppo.state( 'E' )
A = cpppo.state_input( 'A' )
B = cpppo.state_input( 'B', terminal=True )
E['a'] = A
A['b'] = B
B['b'] = B
BASIC = cpppo.dfa( 'ab+', initial=E, context='basic' )
# Composite state machine accepting ab+, ignoring ,[ ]* separators
ABP = cpppo.dfa( 'ab+', initial=E, terminal=True )
SEP = cpppo.state_drop( 'SEP' )
ABP[','] = SEP
SEP[' '] = SEP
SEP[None] = ABP
CSV = cpppo.dfa( 'CSV', initial=ABP, context='csv' )
# A regular expression; he default dfa name is the regular expression itself.
REGEX = cpppo.regex( initial='(ab+)((,[ ]*)(ab+))*', context='regex' )
data = cpppo.dotdict()
for machine in [ BASIC, CSV, REGEX ]:
path = machine.context() + '.input' # default for state_input data
source = cpppo.peekable( str( 'abbbb, ab' ))
with machine:
for i,(m,s) in enumerate( machine.run( source=source, data=data )):
print( "%s #%3d; next byte %3d: %-10.10r: %r" % (
m.name_centered(), i, source.sent, source.peek(), data.get(path) ))
print( "Accepted: %r; remaining: %r\n" % ( data.get(path), ''.join( source )))
print( "Final: %r" % ( data ))
if __name__ == "__main__":
sys.exit( main() )