python——有限状态机

前言

使用Python,大部分时间花在了处理文本上。在处理文本的时候,如果对有限状态机有所了解的话,处理起来会更加得心应手。可以把文本看成一个流,然后有一个机器对这个流进行操作。这个机器有状态,不同的状态会做出不同的处理,状态会随着处理进行变化。

例子

oracle数据库中有一个存储过程,该存储过程中有很多select语句,要把所有的select语句提取出来。

代码:

--存储过程代码
create or replace procedure demo()
is
begin

    insert into table_1
    select a1,a2,a3 
      from table_2;

    insert into table_1
    select a1,a2,a3 
      from table_3;

    insert into table_1
    select a1,a2,a3 
      from table_4;

    commit;

exception
    when others then
        insert into table_log(error_msg)values(sqlerrm);

end;
#python代码
def parse(s):
    l=[]
    state=0  #状态
    for i in s:
        if state==0: #状态为0的处理
            if 'select' in i:
                l.append(i)
                state=1 #状态改变
            if ';' in i:
                state=0
        elif state==1: #状态为1的处理
            l.append(i)
            if ';' in i:
                state=0 #状态改变
    return l

结果:

    select a1,a2,a3 
      from table_2;
    select a1,a2,a3 
      from table_3;
    select a1,a2,a3 
      from table_4;
原文地址:https://www.cnblogs.com/zhizhou/p/3260867.html