4

我有一个表单文本,name(sum(value1,sum(value2,value3)), "sumname")pyparsing 返回适当的标记,但是,我有兴趣取回真实的文本,但我找不到方法。

我已经尝试使用函数 setParseAction,但由于它只返回字符串和位置,我无法处理尾随部分。就像,我只会得到:

"sum(value2,value3)), "sumname")"
"sum(value1,sum(value2,value3)), "sumname")"
"name(sum(value1,sum(value2,value3)), "sumname")"

这并不理想,我不想手动重新解析字符串以获得实际的原始字符串。

我尝试atm的方式是:

tokens = grammar.parseString(target_string)  
print >>sys.stderr, pyparsing.originalTextFor(tokens)

但这并没有真正起作用:

AttributeError: 'NoneType' object has no attribute 'setParseAction'
4

2 回答 2

3

Wrap your expression in the pyparsing helper originalTextFor.

from pyparsing import makeHTMLTags, originalTextFor

sample = '<tag attr1="A1" attr2="B3">'

openTag = makeHTMLTags('tag')[0]

# the expression returned by makeHTMLTags parses the tag and 
# attributes into a list (along with a series of helpful 
# results names)
print (openTag.parseString(sample).asList())

# prints
# ['tag', ['attr1', 'A1'], ['attr2', 'B3'], False]

# wrap in 'originalTextFor' to get back the original source text
print (originalTextFor(openTag).parseString(sample).asList())

# prints
# ['<tag attr1="A1" attr2="B3">']
于 2013-07-01T00:54:14.507 回答
2

根据您通过获取原始匹配文本尝试完成的任务,您可能会使用scanStringor找到更好的解决方案transformString

from pyparsing import makeHTMLTags, replaceWith

sample = '<other><div></div><tag attr1="A1" attr2="B3"><something>'
openTag = makeHTMLTags('tag')[0]

# grammar.scanString is a generator, yielding tokens,start,end tuples
# from the start:end values you can slice the original text from the
# source string
for tokens,start,end in openTag.scanString(sample):
    print tokens.dump()
    print sample[start:end]

# if your goal in getting the original data is to do some kind of string
# replacement, use transformString - here we convert all <TAG> tags to <REPLACE> tags
print openTag.setParseAction(replaceWith("<REPLACE>")).transformString(sample)

印刷:

['tag', ['attr1', 'A1'], ['attr2', 'B3'], False]
- attr1: A1
- attr2: B3
- empty: False
- startTag: ['tag', ['attr1', 'A1'], ['attr2', 'B3'], False]
  - attr1: A1
  - attr2: B3
  - empty: False
  - tag: tag
- tag: tag
<tag attr1="A1" attr2="B3">
<other><div></div><REPLACE><something>

按照这些链接了解有关scanStringtransformString的更多信息。

于 2013-07-01T18:43:16.933 回答