編譯原理----詞法分析程序----python語言版


對python的應用還是不熟練,很多實用的方法沒掌握,下面的程序本來是用C寫的,為了練習一下python,又用python改寫的,很粗糙,有bug,不過能運行出結果,嘿嘿,以后學好了python再來優化吧
#  -*- coding: cp936 -*-
Keyword = ( " begin ", " end ", " if ", " while ", " var ", " procedure ", " else ", " for ", " do ", " int ", " read ", " write ")
Yunsuanfu = ( ' + ', ' - ', ' * ', ' / ', ' < ', ' > ', ' % ', ' = ')
Fenjiefu = ( ' , ', ' ; ', ' ( ', ' ) ', ' { ', ' } ', ' : ')
Kongbai = ( '   ', ' \t ', ' \n ')
Number = ( ' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ')

test= " var a=10;\nvar b,c;\nprocedure p; \n\tbegin\n\t\tc=a+b\n\tend\n "
print test
length=len(test)

for i  in range(length):
     if test[i]  in Kongbai:
         continue
     if test[i]  in Fenjiefu:
         print  " 分界符\t ",test[i]
         continue
     if test[i]  in Yunsuanfu:
         print  " 運算符\t ",test[i]
         continue
     if test[i-1]  in Number:
         continue
     if test[i]  in Number:
         print  " 數字\t ",
         while test[i]  in Number:
             print test[i],
            i+=1
         print  ''
     if test[i-1]  in Number  or (test[i-1]>= ' a '  and test[i-1]<= ' z '):
         continue
    j=0
    temp =  ""
     while True:
         if test[i]  in Kongbai  or test[i]  in Yunsuanfu  or test[i]  in Fenjiefu:
             break
         else:
            j+=1
        i+=1
    temp = test[i-j:i]    
     if temp  in Keyword:
         print  " 關鍵字\t ",temp
     else:
         print  " 標識符\t ",temp

2012年3月21日 22:43:52改寫的代碼:

 1  #  -*- coding: cp936 -*-
 2  Keyword = ( " begin ", " end ", " if ", " while ", " var ", " procedure ", " else ", " for ", " do ", " int ", " read ", " write ")
 3 Yunsuanfu = ( ' + ', ' - ', ' * ', ' / ', ' < ', ' > ', ' % ', ' = ')
 4 Fenjiefu = ( ' , ', ' ; ', ' ( ', ' ) ', ' { ', ' } ', ' : ')
 5 Kongbai = ( '   ', ' \t ', ' \n ')
 6 
 7 test= " var a=10;\nvar b,c;\nprocedure p; \n\tbegin\n\t\tc=a+b\n\tend\n "
 8  print test
 9 length=len(test)
10 i=-1
11  while i < length:
12     i+=1
13      if test[i]  in Kongbai:
14          continue
15      if test[i]  in Fenjiefu:
16          print  " 分界符\t ",test[i]
17          continue
18      if test[i]  in Yunsuanfu:
19          print  " 運算符\t ",test[i]
20          continue
21      if test[i].isdigit():
22          print  " 數字\t ",
23          while test[i].isdigit():
24              print test[i],
25             i+=1
26          print  ''
27         i-=1
28          continue
29     j=0
30     temp =  ""
31      while True:
32          if test[i]  in Kongbai  or test[i]  in Yunsuanfu  or test[i]  in Fenjiefu:
33              break
34          else:
35             j+=1
36         i+=1
37     temp = test[i-j:i]    
38      if temp  in Keyword:
39          print  " 關鍵字\t ",temp
40      else:
41          print  " 標識符\t ",temp

42     i-=1 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM