前言
使用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;