Skip to content

Commit

Permalink
演示解析数组
Browse files Browse the repository at this point in the history
  • Loading branch information
nobodxbodon committed Mar 1, 2024
1 parent bcac6b5 commit d26dcf2
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
2 changes: 1 addition & 1 deletion rply/分词器.py
@@ -1,7 +1,7 @@
from rply.报错 import 分词报错, 按语法分词报错
from rply. import 字符位置,

调试细节 = 0
调试细节 = 1
class 分词器(object):
def __init__(自身, 词规则, 略过规则):
自身.词规则 = 词规则
Expand Down
42 changes: 41 additions & 1 deletion tests/test_按语法分词.py
Expand Up @@ -728,4 +728,44 @@ def 常量(片段):

assert 分析器.按语法分词(分词器.分词(
'添加读者记录,邮箱为“test@example.com”,出生年为2000。'), 25) \
== 'INSERT INTO 读者 (邮箱, 出生年) VALUES ("test@example.com", 2000);'
== 'INSERT INTO 读者 (邮箱, 出生年) VALUES ("test@example.com", 2000);'


def test_数组(self):
分词母机 = 分词器母机()
分词母机.添了("左括号", r"\[")
分词母机.添了("右括号", r"\]")
分词母机.添了("减", r"-")
分词母机.添了("数", r"\d\s*")

分析器母机 = 语法分析器母机(["数", "左括号", "右括号", "减"])

@分析器母机.语法规则("数组 : 左括号 数列 右括号")
def 数组(p):
return p[1]

@分析器母机.语法规则("数列 : 正负数")
@分析器母机.语法规则("数列 : 数列 正负数")
def 数列(片段):
if len(片段) == 1:
return [片段[0]]
if len(片段) == 2:
return 片段[0] + [片段[1]]

@分析器母机.语法规则("正负数 : 数")
@分析器母机.语法规则("正负数 : 减 数")
def 正负数(片段):
if len(片段) == 1:
return int(片段[0].getstr().strip())
if len(片段) == 2:
return -int(片段[1].getstr().strip())

分词器 = 分词母机.产出()
分析器 = 分析器母机.产出()

assert 分析器.按语法分词(分词器.分词('[1]')) == [1]
assert 分析器.按语法分词(分词器.分词('[-1]')) == [-1]
assert 分析器.按语法分词(分词器.分词('[1 3]')) == [1, 3]
assert 分析器.按语法分词(分词器.分词('[-1 3]')) == [-1, 3]
assert 分析器.按语法分词(分词器.分词('[1 -2 3]')) == [1, -2, 3]
assert 分析器.按语法分词(分词器.分词('[1 -2 3 -4 5 6 -7]')) == [1, -2, 3, -4, 5, 6, -7]

0 comments on commit d26dcf2

Please sign in to comment.