可爱的 Python:使用状态机
2007-03-29 12:01:01 来源:WEB开发网Txt2Html 阅读器的一般功能如下:
在初始状态中启动。
读取一行输入。
根据输入和当前状态,转移到新状态或按适合当前状态的方式处理该行。
这个例子是关于您会遇到的最简单的情况,但它说明了我们描述过的以下模式:
Python 中一个简单的状态机输入循环
global
state, blocks, bl_num, newblock
#-- Initialize the globals
state = "HEADER"
blocks = [""]
bl_num = 0
newblock = 1
for
line
in
fhin.readlines():
if
state ==
"HEADER":
# blank line means new block of header
if
blankln.match(line): newblock = 1
elif
textln.match(line): startText(line)
elif
codeln.match(line): startCode(line)
else
:
if
newblock: startHead(line)
else
: blocks[bl_num] = blocks[bl_num] + line
elif
state ==
"TEXT":
# blank line means new block of text
if
blankln.match(line): newblock = 1
elif
headln.match(line): startHead(line)
elif
codeln.match(line): startCode(line)
else
:
if
newblock: startText(line)
else
: blocks[bl_num] = blocks[bl_num] + line
elif
state ==
"CODE":
# blank line does not change state
if
blankln.match(line): blocks[bl_num] = blocks[bl_num] + line
elif
headln.match(line): startHead(line)
elif
textln.match(line): startText(line)
else
: blocks[bl_num] = blocks[bl_num] + line
else
:
raise
ValueError,
"unexpected input block state: "+state
更多精彩
赞助商链接