Boolean parser..

Paul McGuire ptmcg at austin.rr.com
Fri Oct 5 11:27:54 EDT 2007


On Oct 5, 7:00 am, Abandoned <best... at gmail.com> wrote:
> http://pyparsing.wikispaces.com/space/showimage/searchparser.pythis
> is searchparser but i can't understant to use this.
> Can anybody explain this how to use ?

The code demonstrates a testing example, named TestParser, which
inherits from SearchQueryParser.  As mentioned in the docstrings at
the top, to use this code, import the module and define your own class
to inherit from SearchQueryParser.  Then override the Get... methods,
as is done in TestParser.  Each Get method returns a set, and all sets
are then ANDed and ORed according to the input search string.

Here's a simple example, a database of fruit-based products.  To keep
things simple, each product will come from a single fruit, and the
name of the fruit will be at the beginning of the product's name, for
instance "grape juice" is made from the fruit named "grape".

from searchparser import SearchQueryParser

products = [ "grape juice", "grape jelly", "orange juice", "orange
jujubees",
    "strawberry jam", "prune juice", "prune butter", "orange
marmalade",
    "grapefruit juice" ]

class FruitSearchParser(SearchQueryParser):
    def GetWord(self, word):
        return set( p for p in products if p.startswith(word + " ") )

    def GetWordWildcard(self, word):
        return set( p for p in products if p.startswith(word[:-1]) )

    def GetQuotes(self, search_string, tmp_result):
        result = Set()
        # I have no idea how to use this feature...
        return result

    def GetNot(self, not_set):
        return set( products ) - not_set


parser = FruitSearchParser()

tests = """\
    grape or orange
    grape*
    not(grape*)
    prune and grape""".splitlines()

for t in tests:
    print t.strip()
    print parser.Parse(t)
    print


Prints:

grape or orange
set(['orange juice', 'grape juice', 'orange marmalade', 'orange
jujubees', 'grape jelly'])

grape*
set(['grapefruit juice', 'grape juice', 'grape jelly'])

not(grape*)
set(['orange jujubees', 'orange juice', 'prune butter', 'orange
marmalade', 'strawberry jam', 'prune juice'])

prune and grape
set([])






More information about the Python-list mailing list