在pyparsing期间更改字符串 [英] change string during pyparsing

查看:51
本文介绍了在pyparsing期间更改字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 pyparsing 代码中,我有以下表达式:

In my pyparsing code I have the following expressions:

exp1 = Literal("foo") + Suppress(Literal("="))  + Word(alphanums+'_-')
exp2 = Literal("foo") + Suppress(Literal("!=")) + Word(alphanums+'_-')
exp = Optional(exp1) & Optional(exp2)

我想把exp2中的foo改成bar,这样我就可以区分解析数据中的=和!=了.这可能吗?

I want to change foo in exp2 to bar, so that I can distinguish between = and != in the parsed data. Is this possible?

推荐答案

Karl Knechtel 的评论是有效的,但如果您想更改匹配的标记,您可以在解析操作中执行此操作.

Karl Knechtel's comment is valid, but if you want to change a matched token, you can do this in a parse action.

def changeText(s,l,t):
    return "boo" + t[0]

expr = Literal("A").setParseAction(changeText) + "B"
print expr.parseString("A B").asList()

将打印:

['booA', 'B']

如果只想用常量字符串替换表达式,请使用replaceWith:

If you just want to replace an expression with a constant literal string, use replaceWith:

expr = Literal("A").setParseAction(replaceWith("Z")) + "B"
print expr.parseString("A B").asList()

印刷品:

['Z', 'B']

这篇关于在pyparsing期间更改字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆