我最終的目標是應用sql-where-clause-style查詢來過濾熊貓數據框。一些搜索引導我使用pyparsing的infixNotation方法。將中綴插入到解析樹中:只有一個操作符在樹中結束?
我發現中間符號在這裏的一個例子:http://nullege.com/codes/show/src%40p%40y%40pyparsing-2.0.2%40examples%40simpleBool.py/15/pyparsing.infixNotation/python#
但實際處理的符號,我需要多次使用樹在不同的數據。尋找解析樹的幫助我發現這個: http://pyparsing.wikispaces.com/file/view/fourFn.py/30154950/fourFn.py
我從那裏拿到了堆棧實現。然而,這並不像我期望的那樣行事,所以我希望有人能告訴我我做錯了什麼。
這是我能想出的最簡單的例子:
from pyparsing import Word, alphas, infixNotation, opAssoc
exprStack=[]
def pushFirst(strg, loc, toks):
exprStack.append(toks[0])
def addAnd():
exprStack.append("and")
varname = Word(alphas).setParseAction(pushFirst)
operators=[("and", 2, opAssoc.LEFT,addAnd)]
whereExpr = infixNotation(varname,operators)
exprStack=[]
teststring = "cheese and crackers and wine"
parsed=whereExpr.parseString(teststring)
for p in exprStack:
print p
我從這個代碼得到的是:
cheese
crackers
wine
and
我希望得到的,從我如何綴的理解符號法應該可以工作,是:
cheese
crackers
wine
and
and
我也試着用「芝士和餅乾,贏了」電子和嗚嗚聲「但我仍然只有一個」和「在我的名單中。
我在使用infixNotation方法時有什麼誤解?
謝謝
我最終放棄中端協議棧的方法,並使用保麥圭爾的首選對象的方法。對於任何正在尋找應用於熊貓數據框的SQL-where-type查詢的人,你可以在github上找到一個版本(只有有限的語法):[link](https://github.com/moink/askapanda) – moink