使用pyparsing在python中解析文本文件

使用pyparsing在python中解析文本文件,python,pyparsing,Python,Pyparsing,我正在尝试使用pyparsing解析以下文本 acp (SOLO1, "solo-100", "hi here is the gift" "Maximum amount of money, goes", 430, 90) jhk (SOLO2, "solo-101", "hi here goes the wind." "and, they go beyond", 1000, 320) 我已经尝试了以下代码,但它不

我正在尝试使用pyparsing解析以下文本

acp (SOLO1,
     "solo-100",
     "hi here is the gift"
     "Maximum amount of money, goes",
     430, 90)

jhk (SOLO2,
     "solo-101",
     "hi here goes the wind."
     "and, they go beyond",
     1000, 320)
我已经尝试了以下代码,但它不起作用

flag = Word(alphas+nums+'_'+'-')
enclosed = Forward()
nestedBrackets = nestedExpr('(', ')', content=enclosed)
enclosed << (flag | nestedBrackets)

print list(enclosed.searchString (str1))
flag=Word(alphas+nums+''+'-')
封闭=向前()
Nested括号=nestedExpr(“(”,“)”,内容=封闭)

随函附上好吧,我的评论可能有点过于简单化了——下面是一个更完整的例子 回答

如果您真的不需要处理嵌套的数据项,那么可以使用括号中的单个级别 每个部分中的数据组如下所示:

LPAR,RPAR = map(Suppress, "()")
ident = Word(alphas, alphanums + "-_")
integer = Word(nums)

# treat consecutive quoted strings as one combined string
quoted_string = OneOrMore(quotedString)
# add parse action to concatenate multiple adjacent quoted strings
quoted_string.setParseAction(lambda t: '"' + 
                            ''.join(map(lambda s:s.strip('"\''),t)) + 
                            '"' if len(t)>1 else t[0])
data_item = ident | integer | quoted_string

# section defined with no nesting
section = ident + Group(LPAR + delimitedList(data_item) + RPAR)
我不确定你是否有意省略了逗号 两个连续的带引号的字符串,所以我选择实现类似Python编译器的逻辑, 其中,两个带引号的字符串仅被视为一个较长的字符串,即
“AB CD”“EF”
“AB CD EF”
相同。这是通过定义quoted_字符串完成的,并添加 对引用的字符串的解析操作,用于连接2个或更多组件的内容 带引号的字符串

最后,我们为整个组创建一个解析器

results = OneOrMore(Group(section)).parseString(source)
results.pprint()
并从您发布的输入示例中获取:

[['acp',
  ['SOLO1',
   '"solo-100"',
   '"hi here is the giftMaximum amount of money, goes"',
   '430',
   '90']],
 ['jhk',
  ['SOLO2',
   '"solo-101"',
   '"hi here goes the wind.and, they go beyond"',
   '1000',
   '320']]]
如果您确实有嵌套的括号组,则可以使用节定义 就这么简单:

# section defined with nesting
section = ident + nestedExpr()
尽管您已经发现,这将保留单独的逗号,就像它们
是重要的标记,而不仅仅是数据分隔符。

无需使用前向定义nestedExpr-nestedExpr将处理所有插入式嵌套。为此,您只需要
section=flag+nestedExpr(content=Word(nums)| flag | quotedString)
然后解析
一个或多个(section)