-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdemo.py
73 lines (56 loc) · 2.29 KB
/
demo.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# -*- coding: utf-8 -*-
"""Generate an automaton diagram for the given regular expression.
Currently only the following operators are supported: | and * son you can use regular expressions
such as: (a|b)c or ((a|b))*
"""
from __future__ import print_function
import sys
import argparse
import pygraphviz as g
from automaton.parser import parse, ParseError
from automaton.nodes import Null
from automaton.state_machine import to_state_machine
def mark_as_accepting_state(graph, node):
graph_node = graph.get_node(node)
graph_node.attr[u'color'] = u'blue'
graph_node.attr[u'label'] = u'λ'
def draw_state_machine(start_node, state_machine, accepting_states, output):
graph = g.AGraph(directed=True, strict=False)
graph.add_node(start_node, label=u'>')
for node, edge in state_machine:
target_node = state_machine[node, edge]
if type(target_node) is Null:
continue
if target_node in accepting_states:
graph.add_node(target_node)
mark_as_accepting_state(graph, target_node)
else:
graph.add_node(target_node, label=u'')
graph.add_node(node, label=u'')
if node in accepting_states:
mark_as_accepting_state(graph, node)
graph.add_edge(node, target_node, label=edge)
graph.layout(prog='circo')
graph.draw(output)
def alphabet(regex):
return "{%s}" % ", ".join(str(i) for i in regex.alphabet())
def main():
parser = argparse.ArgumentParser(__doc__)
parser.add_argument('regex', help='The regular expression')
parser.add_argument('-o', '--output-filename', default='output.png',
help="Output file name. Default 'output.png'")
args = parser.parse_args()
regex_string = args.regex
output_filename = args.output_filename
try:
regex = parse(regex_string).regex()
except ParseError:
print("Unsupported regular expression")
return
start_node, state_machine, accepting_states = to_state_machine(regex)
print(u"Regular Expression:", regex)
print(u"Regular Expression Alphabet (∑):", alphabet(regex))
draw_state_machine(start_node, state_machine, accepting_states, output=output_filename)
print(u"Graph saved as {!r}".format(output_filename))
if __name__ == "__main__":
sys.exit(main())