Python Pyparsing:捕获圆括号内的逗号分隔列表,忽略内部圆括号。

4
我有一个关于如何正确解析以下字符串的问题,该字符串如下:
"(test.function, arr(3,12), "combine,into one")"

转化为以下列表:
['test.function', 'arr(3,12)', '"combine,into one"']

注意:原始字符串中的“list”项不一定由逗号和空格分隔,也可以直接由逗号一个接着一个地分隔两个项,例如test.function,arr(3,12)
基本上,我想要:
1. 解析包含在括号中但不是内部括号的输入字符串。(因此,无法直接使用nestedExpr()) 2. 内部的项由逗号分隔,但是项本身可能包含逗号。
此外,我只能使用scanString()而不能使用parseString()
我在SO上进行了一些搜索,发现了这个这个,但我无法将它们翻译成适合我的问题。
谢谢!
1个回答

1
这应该解决了您的嵌套和引用问题:
sample = """(test.function, arr(3,12),"combine,into one")"""

from pyparsing import (Suppress, removeQuotes, quotedString, originalTextFor, 
    OneOrMore, Word, printables, nestedExpr, delimitedList)

# punctuation and basic elements
LPAR,RPAR = map(Suppress, "()")
quotedString.addParseAction(removeQuotes)

# what are the possible values inside the ()'s?
# - quoted string - anything is allowed inside quotes, match these first
# - any printable, not containing ',', '(', or ')', with optional nested ()'s
#   (use originalTextFor helper to extract the original text from the input
#   string)
value = (quotedString 
         | originalTextFor(OneOrMore(Word(printables, excludeChars="(),") 
                                     | nestedExpr())))

# define an overall expression, with surrounding ()'s
expr = LPAR + delimitedList(value) + RPAR

# test against the sample
print(expr.parseString(sample).asList())

打印:

['test.function', 'arr(3,12)', 'combine,into one']

嗨,保罗,感谢分享这个解决方案。这个解决方案回答了我的问题。我知道originalTextFor()和nestedExpr(),但从未想过以这种方式实现它们。 - Sam Tatasurya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接