如何从字符串中获取动态数量 (n) 个输入,其中 n 是第一个单词?

问题描述 投票:0回答:1

我有一个如下所示的字符串。

"""
1: a
2: a, b
3: a, b, c
"""

我想使用 pyparsing 定义一个动态语法,并在读取每行开头的数字后选取正确的输入数量。如果输入的数量不相同,则应该给出错误。我确实查看了一些文档,但我只找到了

Forward
,而且我不确定是否可以将它用于此类应用程序。如何使用 pyparsing 为此类输入定义语法?

python pyparsing
1个回答
0
投票

一个可能的解决方案(虽然没有使用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'])
© www.soinside.com 2019 - 2024. All rights reserved.