首页 > 解决方案 > 词法分析器将所有外部调用的 txt 文件代码行识别为标识符而不是标记

问题描述

我正在编写一个词法分析器,它将从外部 txt 文件代码(文本)中识别标识符、运算符、整数和数据类型,但它没有逐个令牌识别它并识别它们,而是将每一行识别为标识符

[Image is output of python lexical analyzer code][1]

**Python code for a small lexical analyzer**

import re                                 

tokens = []                               
sample_code = open("file.txt", "r")


for word in sample_code:

   
    if re.match("[a-z]", word) or re.match("[A-Z]", word):
        tokens.append(['IDENTIFIER', word])

    
    elif re.match(".[0-9]", word):
        if word[len(word) - 1] == ';': 
            tokens.append(["INTEGER", word[:-1]])
            tokens.append(['END_STATEMENT', ';'])
        else: 
            tokwns.append(["INTEGER", word])
    
    
    elif word in ['str', 'int', 'bool']: 
        tokens.append(['DATATYPE', word])
    
    
    elif word in '*-/+%=':
        tokens.append(['OPERATOR', word])
    
   

print(tokens, '\n') 

输出在屏幕截图中

file.txt 中的文本(代码)

#Pythonprogramtofindthefactorialofanumberprovidedbytheuser.
num=7
factorial=1
# starts
ifnum<0:
print("Sorry,factorialdoesnotexistfornegativenumbers")
elifnum==0:
print("Thefactorialof0is1")
else:
foriinrange(1,num+1):
factorial=factorial*i
print("Thefactorialof",num,"is",factorial)

标签: pythonlexical-analysis

解决方案


您一次通过每一行,而您应该一次通过一个符号。要一次读取一个符号,首先使用.read文件中的方法(在您使用的位置open)将其作为文本获取,然后使用该方法将其按每一行拆分.split

sample_code = open("file.txt","r").read().split()

正则表达式中也有一些错误。

如果您想获得一系列字母字符,请使用 regex "[a-zA-Z]+"。对于一系列数字,请使用正则表达式"[0-9]+"(实际上,它允许数字前面有零,因此您可能希望使用"([1-9][0-9]*)|0")。


推荐阅读