在查询中多次使用sqlalchemy.sql的功能

时间:2016-08-19 21:21:25

标签: python mysql python-2.7 sqlalchemy

我使用的是sqlalchemy版本0.7.8。我遇到过一个问题,我的用户可以用简单的英语搜索文本,但db中的记录可以在文本之间有特殊字符。因此,如果用户输入" 请尽早到医院"在db我有" 请早点来医院。"那么我的查询必须准确地返回请早点来医院。

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

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

但问题是,db中可能有许多特殊字符,如" ! ; :? &安培; "等针和针将看起来非常低效,所以请建议我任何有效的解决方案,以避免重复func.replace功能。

我无法在stackoverflow上找到相同的问题,如果有人已经回复,请告诉我。

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

使用RegEx

的查询

SqlAlchemy documentation中有一些例子。

另见question

答案 2 :(得分:0)

您可以使用它来删除python中的所有空格字符

>>> impore re
>>> string = "please, come early# to the@ hospital"
>>> cleanString = re.sub('\W+',' ', string )
>>> print cleanString
please come early to the hospital

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