Python使用运算符和布尔值进行高级字符串搜索

ofk*_*fko 5 python google-app-engine

我有一个函数搜索列表列表中的字符串然后返回包含匹配列表的列表:

def foo(myList,keyword,first=True):
    if first: #Search only first element or each sublist
        return [x for x in myList if keyword in x]
    else: #Search first and second elements of each sublist
        return [x for x in myList if keyword in x or keyword in x[1]]
Run Code Online (Sandbox Code Playgroud)

现在我想扩展它来处理高级搜索,例如:

matchthis -butnothis -"and not this"

this|orthis|"or this"

brand new*laptop  # this is a wildcard, matches like: brand new dell laptop

"exact phrase"
Run Code Online (Sandbox Code Playgroud)

是否有我可以在我的函数中使用的python模块(最好是内置的)来处理这些查询?

PS:我知道Swoosh,但它现在不适合我.另外,我目前正在使用App Engine.

我正在尝试做的基本上是内存中的全文搜索,因为app引擎还不支持全文搜索.我查询数据存储区,将实体放入列表并循环遍历这些列表以查找查询匹配项.

And*_*ark 4

我会尝试为搜索查询的每个部分构建一个正则表达式。首先,您可以使用 将查询分成几个部分shlex.split(),然后单独创建每个正则表达式。这是我的破解:

import shlex, re

def foo(query):
    pieces = shlex.split(query)
    include, exclude = [], []
    for piece in pieces:
        if piece.startswith('-'):
            exclude.append(re.compile(piece[1:]))
        else:
            include.append(re.compile(piece))
    def validator(s):
        return (all(r.search(s) for r in include) and
                not any(r.search(s) for r in exclude))
    return validator
Run Code Online (Sandbox Code Playgroud)

这将返回一个可用于验证查询的函数,例如:

>>> test = foo('matchthis -butnothis -"and not this"')
>>> test("we should matchthis...")
True
>>> test("some stuff matchthis blah and not this...")
False
Run Code Online (Sandbox Code Playgroud)

您应该能够通过*在查询中替换为.*正则表达式来添加一些通配符处理。