我需要制定一条规则来评估以下表达式。
Sao Paulo to Rio de Janeiro >> ["Sao Paulo", "Rio de Janeiro"]
Rio de Janeiro to Brasilia >> ["Rio de Janeiro", "Brasilia"]
Brasilia to Sao Jose dos Pinhais >> ["Brasilia", "Sao Jose dos Pinhais"]
我尝试失败了
from pyparsing import *
source = OneOrMore(Word(alphas))
target = OneOrMore(Word(alphas))
expression = source + Literal('to') + target
# input string
phase = "Sao Paulo to Rio de Janeiro"
# parse input string
print phase, "->", expression.parseString( phase )
答案 0 :(得分:3)
问题是OneOrMore(Word(alphas))因为'to'匹配Word(alphas)而贪婪,你需要为它包含一个前瞻。
你可以通过添加一个NOT(aka~)运算符来解决这个问题,该运算符专门寻找'to'并停止匹配。那么问题是,'to'之前的单词不是表达式的一部分。所以你必须在最后添加一个Word(alphas)。
to = Suppress(Literal('to'))
src = Group(ZeroOrMore(Word(alphas) + ~FollowedBy(to)) + Word(alphas)).setResultsName('src')
dst = OneOrMore(Word(alphas)).setResultsName('dst')
exp = src + to + dest
phase = "Sao Paulo to Rio de Janeiro"
# parse input string
s = exp.parseString( phase )
当你运行它时,你会得到你想要的结果:
['Sao', 'Paulo']
['Rio', 'de', 'Janeiro']