【问题标题】:Word boundary RegEx search using PyMongo使用 PyMongo 的词边界 RegEx 搜索
【发布时间】:2016-02-26 04:17:42
【问题描述】:

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

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

并进行搜索以查找整体包含“cook”的条目。即只返回第 3、4、5 个条目。

在这种情况下,当我使用\b 字边界语句时,它会由于自动转义而变得扭曲。

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

当我打印查询字典时,\b 变为 \\b

我的问题是如何使用 PyMongo 进行单词边界搜索?我可以在 MongoDB shell 中执行此操作,但在 PyMongo 中失败了。

【问题讨论】:

标签: python regex mongodb pymongo


【解决方案1】:

不要使用产生str 对象的pattern 属性,而是使用正则表达式模式对象。

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

for doc in cursor:
    # your code

【讨论】:

  • 坦克,它对我有用。你说的对。原因是 str 对象被转义了。
【解决方案2】:

这需要一个“全文搜索”索引来匹配您的所有案例。没有简单的正则表达式就足够了。

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

有许多“全文搜索”索引引擎。研究它们以决定使用哪一个。 - 弹性搜索 - Lucene - 狮身人面像

我认为 PyMongo 连接到 MongoDB。最新版本内置全文索引。见下文。

MongDB 3.0 有这些索引:https://docs.mongodb.org/manual/core/index-text/

【讨论】:

    【解决方案3】:

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

    >>> 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."
    >>> 
    

    【讨论】:

      猜你喜欢
      • 2014-09-27
      • 1970-01-01
      • 1970-01-01
      • 2020-09-15
      • 2012-08-22
      • 2012-03-28
      • 1970-01-01
      • 2014-12-11
      • 2016-02-17
      相关资源
      最近更新 更多