我正在尝试使用 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))
引用中的逗号 (,) 会产生不希望的结果。
最佳答案
嗯,我的评论可能有点过于简单化了 - 这是一个更完整的 回答。
如果您确实不需要处理嵌套数据项,则可以使用单级括号 每个部分中的数据组将如下所示:
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_string 的定义完成的,并添加
对 Quoted_string 进行解析操作以连接 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()
尽管正如您已经发现的那样,这将保留单独的逗号,就好像它们一样 是重要的标记而不仅仅是数据分隔符。
关于python - 使用 pyparsing 在 python 中解析文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31730362/