基于PyMong的词边界正则表达式搜索

2024-05-14 01:27:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个单词边界搜索。例如,假设您有以下条目:

  1. “厨师们。”
  2. “厨师”
  3. “做饭。”
  4. “厨师是”
  5. “做饭。”

并搜索包含“库克”作为一个整体的条目。也就是说,只应返回第3、第4和第5个条目。在

在本例中,当我使用\b单词边界语句时,由于自动转义,它会以某种方式失真。在

import re, pymongo
# prepare pymongo
collection.find({"entry": re.compile('\bcook\b').pattern})

当我打印查询字典时,\b变成{}。在

我的问题是如何使用PyMongo进行单词边界搜索?我可以在mongodbshell中做到这一点,但在PyMongo失败了。在


Tags: importre方式条目语句findprepare单词
3条回答

所有这些测试用例都由Python中的一个简单的重新表达式来处理。示例:

>>> a = "the cooks."
>>> b = "cooks"
>>> c = " cook."
>>> d = "the cook is"
>>> e = "cook."
>>> tests = [a,b,c,d,e]
>>> for test in tests:
        rc = re.match("[^c]*(cook)[^s]", test)
        if rc:
                print '   Found: "%s" in "%s"' % (rc.group(1), test)
        else:
                print '   Search word NOT found in "%s"' % test


   Search word NOT found in "the cooks."
   Search word NOT found in "cooks"
   Found: "cook" in " cook."
   Found: "cook" in "the cook is"
   Found: "cook" in "cook."
>>> 

不要使用生成pattern对象的pattern属性,而是使用regex模式对象。在

cursor = db.your_collection.find({"field": re.compile(r'\bcook\b')})

for doc in cursor:
    # your code

这需要一个“全文搜索”索引来匹配所有案例。简单的正则表达式是不够的。在

例如,您需要英语词干来查找“cook”和“cooks”。正则表达式匹配空格或单词边界之间的整个字符串“cook”,而不是“cooks”或“cooking”。在

有许多“全文搜索”索引引擎。研究他们决定使用哪一个。 -弹性搜索 -鲁辛 -斯芬克斯

我想PyMongo连接到MongoDB。最新版本有内置的全文索引。见下文。在

mongdb3.0有以下索引:https://docs.mongodb.org/manual/core/index-text/

相关问题 更多 >