2015-11-23 47 views
2

我想進行詞邊界搜索。例如,假設您有以下條目:使用PyMongo的Word邊界RegEx搜索

  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中失敗。

+0

我認爲它需要'\\ \\ bcook B' –

+0

是,'\ bcook \ B'變成'\\ \\ bcook B' – Muatik

+0

試試['R'\ bcook \ b 「'](http://stackoverflow.com/questions/2241600/python-regex-r-prefix)。 – Sam

回答

2

而不是使用pattern屬性產生str對象,請使用正則表達式模式對象。

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

for doc in cursor: 
    # your code 
+0

坦克,它適合我。你是對的。原因是str對象正在逃脫。 – Muatik

1

這需要一個「全文搜索」索引來匹配您的所有案例。沒有簡單的RegEx足夠。

例如,您需要英語詞幹找到「廚師」&「廚師」。您的RegEx匹配空格或單詞邊界之間的整個字符串「cook」,而不是「廚師」或「烹飪」。

有許多「全文搜索」索引引擎。研究他們決定使用哪一個。 - ElasticSearch - Lucene - Sphinx

PyMongo,我假設,連接到MongoDB。最新版本內置全文索引。見下文。

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

0

所有這些測試病例是由在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." 
>>>