How to get a dynamic number (n) of inputs from a string, where n is the first word?

51 views Asked by At

I have a string which looks like the following.

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

I would like to use pyparsing to define a grammar which is dynamic and picks up the correct number of inputs after reading the number in the beginning of each line. If the number of inputs are not the same, it should give an error. I did look into some documentation, but I only found Forward, and I am not sure if I can use it for this sort of an application. How do I define grammar for this sort of an input using pyparsing?

1

There are 1 answers

0
fanfly On

A possible solution (although pyparsing is not used):

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

When the given integer does not match the number of strings, an exception is raised:

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'])