python - 词法分析器将所有外部调用的 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)
解决方案
您一次通过每一行,而您应该一次通过一个符号。要一次读取一个符号,首先使用.read
文件中的方法(在您使用的位置open
)将其作为文本获取,然后使用该方法将其按每一行拆分.split
:
sample_code = open("file.txt","r").read().split()
正则表达式中也有一些错误。
如果您想获得一系列字母字符,请使用 regex "[a-zA-Z]+"
。对于一系列数字,请使用正则表达式"[0-9]+"
(实际上,它允许数字前面有零,因此您可能希望使用"([1-9][0-9]*)|0"
)。
推荐阅读
- firebase - Firebase 按键
- python - python - 将时间序列事件转换为开关对
- linux - Bash 转义字符
- python - 检查 List 是否是 List 保持秩序的一部分并找到职位
- android - 如何在 mvvm 架构中实现 BaseActivity?不使用依赖注入
- biztalk - BizTalk 在部署时丢失端口绑定
- javascript - 在 MongoDB 中插入包含随机数据的文档
- mysql - mysql中的子字符串正则表达式匹配
- php - 将 Catalina 更新为 Big Sur apache 错误 /private/etc/apache2/httpd.conf: 无法打开配置文件 /private/etc/apache2/other/+php-osx.conf
- php - Laravel 关系的序列化关系数组