import re
class LexicalAnalyzer:
def __init__(self):
self.keywords = {
'main': 1, 'if': 2, 'then': 3, 'while': 4, 'do': 5,
'static': 6, 'int': 7, 'double': 8, 'struct': 9,
'break': 10, 'else': 11, 'long': 12, 'switch': 13,
'case': 14, 'typedef': 15, 'char': 16, 'return': 17,
'const': 18, 'float': 19, 'short': 20, 'continue': 21,
'for': 22, 'void': 23, 'sizeof': 24, 'ID': 25,
'NUM': 26
}
self.operators = {
'+': 27, '-': 28, '*': 29, '/': 30, '=': 38,
'==': 32, '!=': 33, '<': 34, '<=': 35,
'>': 36, '>=': 37, ':': 31, ':=': 32,
';': 41, '(': 42, ')': 43, '#': 0,'{':50,'}':51
}
self.tokens = []
self.symbol_table = {}
def pre_process(self, content):
content = re.sub(r'//.*?\n', ' ', content)#去除单行注释
content = re.sub(r'/\*.*?\*/', ' ', content, flags=re.DOTALL)#去除多行注释
content = re.sub(r'[\t\r\n]+', ' ', content)#去除回车,换行,制表等
content = re.sub(r' +', ' ', content)#替换多个空格为一个空格
return content.strip()
def tokenize(self, content):
tokens = []
# 优先匹配二元运算符
regex = r'(".*?"|==|!=|<=|>=|[+\-*/=<>:;(){}#]|\d+\.\d+|\d+|[a-zA-Z_]\w*|\s+)'
matches = re.finditer(regex, content)#返回全部匹配对象
for match in matches:
token = match.group(0)
if token in self.keywords:
tokens.append((self.keywords[token], token, -1))
elif re.match(r'^\d+\.\d+$', token): # 匹配浮点数
tokens.append((26, token, float(token))) # NUM 返回实际数字
elif re.match(r'^\d+$', token): # 匹配整数
tokens.append((26, token, int(token))) # NUM 返回实际数字
elif re.match(r'^[a-zA-Z_]\w*$', token): # 确保标识符以字母或下划线开头
tokens.append((25, token, -1)) # ID 返回 -1
elif re.match(r'^[0-9]', token): # 识别以数字开头的标识符
print(f"错误: 标识符 '{token}' 不能以数字开头")
elif re.match(r'^".*"$', token): # 识别字符串
tokens.append((27, token, -1)) # 假设字符串的种别码为 27
elif token in self.operators:
tokens.append((self.operators[token], token, -1)) # 运算符和符号
elif token.strip() == '':
continue # 忽略空白字符
return tokens
def analyze(self, file_path):
try:
with open(file_path, 'r', encoding='utf-8') as infile:
content = infile.read()
except FileNotFoundError:
print("读取文件失败")
return
processed_content = self.pre_process(content)
self.tokens = self.tokenize(processed_content)
def display_tokens(self):
print(f"{'syn':<10} {'token':<20} {'NUM':<10}") # 表头
print("-" * 40) # 分隔线
for code, token, num in self.tokens:
print(f"{code:<10} {token:<20} {num:<10}")
def display_symbol_table(self):
print("\nSymbol Table:")
# 输出关键字
for symbol, code in self.keywords.items():
print(f"<{code}: {symbol}>")
# 输出操作符
for symbol, code in self.operators.items():
print(f"<{code}: {symbol}>")
def main():
analyzer = LexicalAnalyzer()
input_file_path = "D:\\test.txt"
analyzer.analyze(input_file_path)
analyzer.display_tokens()
analyzer.display_symbol_table()
if __name__ == "__main__":
main()
代码里面的文件路径改成自己的即可,实验报告在主页资源里面,可以对照着参考(实验报告用AI写的,仅作为参考,代码验收时评分为A+,但最后成绩没满绩,所以想满绩还是好好写报告吧)
271




被折叠的 条评论
为什么被折叠?



