请帮我写一个词法分析程序
时间: 2023-08-28 22:30:03 浏览: 41
好的,以下是一个简单的词法分析程序,可以对输入的代码进行基本的词法分析:
```python
import re
# 定义词法单元的类型
TOKEN_TYPES = [
('NUM', r'\d+(\.\d*)?'), # 数字
('ID', r'[a-zA-Z]\w*'), # 标识符
('OP', r'[+\-*/%]'), # 运算符
('ASSIGN', r'='), # 赋值符号
('LPAREN', r'\('), # 左括号
('RPAREN', r'\)'), # 右括号
('WHITESPACE', r'\s+'), # 空格
]
# 定义 Token 类
class Token:
def __init__(self, type, value):
self.type = type
self.value = value
def __str__(self):
return f'Token({self.type}, {self.value})'
# 定义 Lexer 类
class Lexer:
def __init__(self, text):
self.text = text
self.pos = 0
def tokenize(self):
tokens = []
while self.pos < len(self.text):
match = None
for token_type in TOKEN_TYPES:
pattern = token_type[1]
regex = re.compile(pattern)
match = regex.match(self.text, self.pos)
if match:
type = token_type[0]
value = match.group(0)
token = Token(type, value)
tokens.append(token)
self.pos = match.end(0)
break
if not match:
raise Exception(f'Invalid token: {self.text[self.pos]}')
return tokens
```
使用示例:
```python
text = 'x = 42 + y * 3'
lexer = Lexer(text)
tokens = lexer.tokenize()
for token in tokens:
print(token)
```
输出结果:
```
Token(ID, x)
Token(ASSIGN, =)
Token(NUM, 42)
Token(OP, +)
Token(ID, y)
Token(OP, *)
Token(NUM, 3)
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)