Jak*_*ube 4 python pyparsing python-2.7
在我的pyparsing代码中,我有以下表达式:
exp1 = Literal("foo") + Suppress(Literal("=")) + Word(alphanums+'_-')
exp2 = Literal("foo") + Suppress(Literal("!=")) + Word(alphanums+'_-')
exp = Optional(exp1) & Optional(exp2)
Run Code Online (Sandbox Code Playgroud)
我想将exp2中的foo更改为bar,以便我可以在已解析的数据中区分=和!=.这可能吗?
Karl Knechtel的评论是有效的,但如果您想更改匹配的令牌,可以在解析操作中执行此操作.
def changeText(s,l,t):
return "boo" + t[0]
expr = Literal("A").setParseAction(changeText) + "B"
print expr.parseString("A B").asList()
Run Code Online (Sandbox Code Playgroud)
将打印:
['booA', 'B']
Run Code Online (Sandbox Code Playgroud)
如果您只想用常量文字字符串替换表达式,请使用replaceWith:
expr = Literal("A").setParseAction(replaceWith("Z")) + "B"
print expr.parseString("A B").asList()
Run Code Online (Sandbox Code Playgroud)
打印:
['Z', 'B']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
844 次 |
| 最近记录: |