如何用python寫一個(gè)簡(jiǎn)單的詞法分析器
編譯原理老師要求寫一個(gè)java的詞法分析器,想了想決定用python寫一個(gè)。
目標(biāo)
能識(shí)別出變量,數(shù)字,運(yùn)算符,界符和關(guān)鍵字,用excel表打印出來。
有了目標(biāo),想想要怎么實(shí)現(xiàn)詞法分析器。
1.先進(jìn)行預(yù)處理,把注釋,多余的空格,空行去掉。
2.一行一行掃描,行里逐字掃描,把界符和運(yùn)算符當(dāng)做分割符,遇到就先停下開始判斷。
- 若是以 英文字母、$、下劃線開頭,則可能是變量和關(guān)鍵字,在判斷是關(guān)鍵字還是變量。
- 若是數(shù)字開頭,則判斷下一位是不是也是數(shù)字,直到遇到非數(shù)字停止,在把數(shù)字取出來。
- 再來判斷分割符是什么類型,是界符還是運(yùn)算符。
在給不同詞添加上識(shí)別碼
在用excel表打印出來。
代碼實(shí)現(xiàn)
1. 用列表創(chuàng)建一個(gè)關(guān)鍵字表,java關(guān)鍵字有50個(gè)。
#保留字
key_word = ['abstract','assert','boolean','break','byte',
'case','catch','char','class','const',
'continue','default','do','double','else',
'enum','extends','final','finally','float',
'for','goto','if','implements','import',
'instanceof','int','interface','long','native',
'new','package','private','protected','public',
'return','short','static','strictfp','super',
'switch','synchronized','this','throw','throws',
'transient','try','void','volatile','while']
2.用列表創(chuàng)建一個(gè)運(yùn)算符表。
#運(yùn)算符
operator = ['+','-','*','/','%','++','--','+=','-=','+=','/=',#算術(shù)運(yùn)算符
'==','!=','>','<','>=','<=',#關(guān)系運(yùn)算符
'&','|','^','~','<<','>>','>>>',#位運(yùn)算符
'&&','||','!',#邏輯運(yùn)算符
'=','+=','-=','*=','/=','%=','<<=','>>=','&=','^=','|=',#賦值運(yùn)算符
'?:']#條件運(yùn)算符
3. 用列表創(chuàng)建一個(gè)界符表。
#界符
delimiters = ['{','}','[',']','(',')','.',',',':',';']
4.預(yù)處理
用正則表達(dá)式把注釋去掉,在把多余的空行去掉
#預(yù)處理
def filterResource(file,new_file):
f2 = open(new_file,'w+')
txt = ''.join(open(file,'r').readlines())
deal_txt = re.sub(r'\/\*[\s\S]*\*\/|\/\/.*','',txt)
for line in deal_txt.split('\n'):
line = line.strip()
line = line.replace('\\t','')
line = line.replace('\\n','')
if not line:
continue
else:
f2.write(line+'\n')
f2.close()
return sys.path[0]+'\\'+ new_file
5.逐行掃描
按照剛剛的思路進(jìn)行判斷,把每一行的單詞,添加到word_line列表中,最后在把每一行添加到token列表中。
def Scan(file):
lines = open(file,'r').readlines()
for line in lines:
word = ''
word_line = []
i = 0
while i <len(line):
word +=line[i]
if line[i]==' ' or line[i] in delimiters or line[i] in operator:
if word[0].isalpha() or word[0]=='$' or word[0]=='_':
word = word[:-1]
if searchReserve(word):
# 保留字
word_line.append({word[:-1]:key_word.index(word)})
else:
# 標(biāo)識(shí)符
identifier.append({word:-2})
word_line.append({word:-2})
# 常數(shù)
elif word[:-1].isdigit():
word_line.append({word:-1})
#else:
#error_word.append(word)
# 字符是界符
if line[i] in delimiters:
word_line.append({line[i]:len(key_word)+delimiters.index(line[i])})
# 字符是運(yùn)算符
elif line[i] in operator:
s = line[i] +line[i+1]
if s in operator:
word_line.append({s:len(key_word)+len(delimiters)+operator.index(s)})
i +=1
else:
word_line.append({line[i]:len(key_word)+len(delimiters)+operator.index(line[i])})
word = ''
i+=1
token.append(word_line)
6.根據(jù)單詞返回是什么類型
按照保留字--界符--運(yùn)算符--常數(shù)的順序來當(dāng)識(shí)別碼。常數(shù)識(shí)別碼是-1,標(biāo)識(shí)符識(shí)別碼是-2
def check(number):
hanzi = ''
q = len(key_word)
w = len(delimiters)
e = len(operator)
if 0<number<=q:
hanzi = '保留字'
elif q<number <= q+w:
hanzi = '界符'
elif q+w<number <=q+w+e:
hanzi = '運(yùn)算符'
elif number == -1:
hanzi ='常數(shù)'
elif number == -2:
hanzi ='標(biāo)識(shí)符'
return hanzi
7. 用thinker寫一個(gè)簡(jiǎn)單的界面
導(dǎo)入
from tkinter import * from tkinter.filedialog import askdirectory,askopenfilename
root = Tk()
root.title('詞法分析')
root.resizable(0, 0)
path = StringVar()
Label(root,text = "目標(biāo)路徑:").grid(row = 0, column = 0)
Entry(root, textvariable = path).grid(row = 0, column = 1)
Button(root, text = "路徑選擇", command = openfiles).grid(row = 0, column = 2)
Button(root,text='詞法分析',command= open_excel).grid(row = 0,column = 3)
root.mainloop()
打開文件
def openfiles():
fname = askopenfilename(title='打開文件', filetypes=[('All Files', '*')])
path.set(fname)

簡(jiǎn)單的界面
8.導(dǎo)入到excel表中
需要安裝包xwings
pip install xwings
導(dǎo)入
import xlwings as xw
把token里的單詞,按照 單詞 ---- 識(shí)別碼 ---類型 打印到excel表中
def open_excel():
# 預(yù)處理
row,col=0,0
if path.get()!='':
txt = java_analysis.filterResource(path.get(),new_file)
print(txt)
#掃描
java_analysis.Scan(txt)
app = xw.App(visible=True,add_book=False)
wb =app.books.open(sys.path[0]+'\\'+'test.xlsx')
sheet = wb.sheets.active
sheet.clear()
print(java_analysis.token)
for i in range(len(java_analysis.token)):
sheet[row,0].value = '第'+str(i+1)+'行'
row +=1
for word in java_analysis.token[i]:
for k,w in word.items():
sheet[row,3].value = k
sheet[row,5].value = w
sheet[row,7].value = java_analysis.check(w)
row +=1
sheet.autofit()#整個(gè)sheet自動(dòng)調(diào)整
#wb.save()
最后就像這樣

效果
代碼很爛,不過也算是大致明白詞法分析器了。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解Python和Rust中內(nèi)存管理機(jī)制的實(shí)現(xiàn)與對(duì)比
Python和Rust都采用了垃圾收集(Garbage?Collection)機(jī)制來管理內(nèi)存,但它們各自的實(shí)現(xiàn)方式有很大的不同,下面就跟隨小編一起來深入了解下二者的區(qū)別吧2024-03-03
Scrapy啟動(dòng)報(bào)錯(cuò)invalid syntax的解決
這篇文章主要介紹了Scrapy啟動(dòng)報(bào)錯(cuò)invalid syntax的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
Python機(jī)器學(xué)習(xí)10大經(jīng)典算法的講解和示例
10個(gè)經(jīng)典的機(jī)器學(xué)習(xí)算法包括:線性回歸、邏輯回歸、K-最近鄰(KNN)、支持向量機(jī)(SVM)、決策樹、隨機(jī)森林、樸素貝葉斯、K-均值聚類、主成分分析(PCA)、和梯度提升(Gradient?Boosting),我將使用常見的機(jī)器學(xué)習(xí)庫(kù),如scikit-learn,numpy和pandas?來實(shí)現(xiàn)這些算法2024-06-06
Union在Python類型注解中的應(yīng)用與最佳實(shí)踐
Union” 在中文中通常翻譯為“聯(lián)合”,在數(shù)學(xué)和邏輯學(xué)中,它指的是兩個(gè)或多個(gè)集合的并集,在 Python 的類型注解中,Union 類型表示一個(gè)變量可以是多種類型中的任意一種,這與數(shù)學(xué)中的并集概念相似,本文介紹了Union在Python類型注解中的應(yīng)用與最佳實(shí)踐2024-09-09
python字符串與url編碼的轉(zhuǎn)換實(shí)例
今天小編就為大家分享一篇python字符串與url編碼的轉(zhuǎn)換實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-05-05
用Python程序抓取網(wǎng)頁(yè)的HTML信息的一個(gè)小實(shí)例
這篇文章主要介紹了用Python程序抓取網(wǎng)頁(yè)的HTML信息的一個(gè)小實(shí)例,用到的方法同時(shí)也是用Python編寫爬蟲的基礎(chǔ),需要的朋友可以參考下2015-05-05
python實(shí)現(xiàn)簡(jiǎn)單井字棋游戲
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)簡(jiǎn)單井字棋游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-03-03

