Python高级字符串搜索与运算符和布尔值

5 投票
2 回答
2034 浏览
提问于 2025-04-17 09:14

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

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]]

现在我想把这个功能扩展一下,让它能处理更复杂的搜索,比如:

matchthis -butnothis -"and not this"

this|orthis|"or this"

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

"exact phrase"

有没有什么Python模块(最好是内置的)可以让我在我的函数中使用,以处理这些查询?

顺便说一下,我知道Swoosh这个东西,但现在对我来说不太合适。而且,我现在使用的是App Engine。

我基本上想做的是在内存中进行全文搜索,因为App Engine目前还不支持全文搜索。我查询数据存储,把实体放到列表里,然后遍历这些列表来找到匹配的查询。

2 个回答

3

没有一个标准的库模块可以完全满足你的需求;不过,你可以先从 shlex模块 开始,这个模块可以帮助你解析搜索组:

>>> import shlex
>>> s = '''matchthis -butnothis -"and not this"
this|orthis|"or this"
brand new*laptop
"exact phrase"
'''
>>> shlex.split(s)
['matchthis', '-butnothis', '-and not this', 'this|orthis|or this', 'brand', 'new*laptop', 'exact phrase']

如果你需要更精细的解析控制,可以看看 re模块

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

这段代码会返回一个函数,你可以用它来验证查询,比如:

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

你应该可以通过将查询中的 * 替换为正则表达式中的 .* 来添加一些通配符的处理。

撰写回答