gpt4 book ai didi

Python Pyparsing : Capture comma-separated list inside parentheses ignoring inner parentheses

转载 作者:太空宇宙 更新时间:2023-11-03 11:45:27 25 4
gpt4 key购买 nike

我有一个关于如何正确解析如下字符串的问题,

"(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 中做了一些搜索并找到了 thisthis ,但我无法将它们翻译成适合我的问题。

谢谢!

最佳答案

这应该可以解决您的嵌套和引用问题:

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

关于Python Pyparsing : Capture comma-separated list inside parentheses ignoring inner parentheses,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40684608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com