在查询中多次使用 sqlalchemy.sql 的函数

Using function of sqlalchemy.sql multiple times in query

我正在使用 sqlalchemy 版本 0.7.8。我遇到了一个问题,我的用户可以用纯英语搜索文本,但数据库中的记录可以在文本之间包含特殊字符。因此,如果用户输入“请早点来医院”并且在数据库中我有“请早点来医院。”然后我的查询必须return完全请早点来医院

我找到了这个简单的解决方案。

needle = func.replace(func.replace(Message.text, ',', ''), '.', '')
Message.query.filter(needle==query_term.strip()).one()

但问题是数据库中可能有很多特殊字符,如“! ; : ? &”等,needle 看起来效率很低,所以请给我一些有效的建议避免重复 func.replace 函数的解决方案。

我在 Whosebug 上找不到相同的问题如果有人已经回答了,请告诉我。

使用 RegEx

的查询

SqlAlchemy documentation中有例子。

另请参阅此 question

您可以使用它来删除 python

中的所有特殊字符
>>> impore re
>>> string = "please, come early# to the@ hospital"
>>> cleanString = re.sub('\W+',' ', string )
>>> print cleanString
please come early to the hospital

将您的文本作为字符串存储在变量中,然后 运行 使用此变量进行查询。

感谢所有回复。我可以通过这种方式改进它。

IGNORE_CHARS = [',', '.', '!', '&', ';', ':', '@']
needle = build_replace_func(IGNORE_CHARS, Message.text)
record = Message.query.filter(needle == query_term.strip()).one()

def build_replace_func(chars, attr, replace_with=''):
    for character in chars:
        attr = func.replace(attr, character, replace_with)
    return attr