一、程序要求(以python为例)。
1.词法分析程序(Lexical Analyzer)要求:
- 从左至右扫描构成源程序的字符流
- 识别出有词法意义的单词(Lexemes)
- 返回单词记录(单词类别,单词本身)
- 滤掉空格
- 跳过注释
- 发现词法错误
2.程序结构:
输入:字符流(什么输入方式,什么数据结构保存)
处理:
–遍历(什么遍历方式)
–词法规则
输出:单词流(什么输出形式)
–二元组
3.单词类别:
1.标识符(10)
2.无符号数(11)
3.保留字(一词一码)
4.运算符(一词一码)
5.界符(一词一码)
单词符号 |
种别码 |
单词符号 |
种别码 |
begin |
1 |
: |
17 |
if |
2 |
:= |
18 |
then |
3 |
< |
20 |
while |
4 |
<= |
21 |
do |
5 |
<> |
22 |
end |
6 |
> |
23 |
l(l|d)* |
10 |
>= |
24 |
dd* |
11 |
= |
25 |
+ |
13 |
; |
26 |
- |
14 |
( |
27 |
* |
15 |
) |
28 |
/ |
16 |
# |
0 |
二、代码实现(以python为例)。
1.词法分析程序。
1 import re 2 3 strs = "if sum >= 1000 then x : x - 1;#"+" " 4 5 types = {'begin':1, 6 'if':2, 7 'then':3, 8 'while':4, 9 'do':5, 10 'end':6, 11 'l(l|d)*':10, 12 'dd*':11, 13 '+':13, 14 '-':14, 15 '*':15, 16 '/':16, 17 ':':17, 18 ':=':18, 19 '<':20, 20 '<=':21, 21 '<>':22, 22 '>':23, 23 '>=':24, 24 '=':25, 25 ';':26, 26 '(':27, 27 ')':28, 28 '#':0 29 } 30 31 if __name__ == '__main__': 32 # strs = input('请输入程序代码:')+" " #补位 33 34 index = 0 35 while index < len(strs): 36 keyIndex = 0 37 for key in types.keys(): 38 if index+len(key) < len(strs): 39 if strs[index:index+len(key)] == key and not re.match('^[=a-zA-Z0-9_-]$', strs[index+len(key)]): 40 if not(strs[index] == '=' and re.match('^[<>]$', strs[index-1])): 41 ss = strs[index:index+len(key)] 42 print((ss, types.get(ss))) 43 elif re.match('^[a-zA-Z0-9_]+', strs[index:]): 44 ss = re.match('^([a-zA-Z0-9_]+)', strs[index:]).group() 45 print((ss, types.get(ss))) 46 index += len(ss) 47 keyIndex+=1 48 index+=1
2.运行结果展示。