我有一个如下所示的字符串。
"""
1: a
2: a, b
3: a, b, c
"""
我想使用 pyparsing 定义一个动态语法,并在读取每行开头的数字后选取正确的输入数量。如果输入的数量不相同,则应该给出错误。我确实查看了一些文档,但我只找到了
Forward
,而且我不确定是否可以将它用于此类应用程序。如何使用 pyparsing 为此类输入定义语法?
一个可能的解决方案(虽然没有使用pyparsing):
def parse(s):
front, back = s.split(': ')
n = int(front)
l = back.split(', ')
if n != len(l):
raise ValueError(
'number of strings is incorrect: {} != len({})'.format(n, l)
)
return n, l
lines = [
'1: a',
'2: a, b, c',
'3: a, b, c',
]
for line in lines:
n, l = parse(line)
# maybe do something with n and l
当给定的整数与字符串的数量不匹配时,会引发异常:
Traceback (most recent call last):
File "/some/path/to/test.py", line 18, in <module>
n, l = parse(line)
^^^^^^^^^^^
File "/some/path/to/test.py", line 6, in parse
raise ValueError(
ValueError: number of strings is incorrect: 2 != len(['a', 'b', 'c'])