【问题标题】:Python text search library [closed]Python文本搜索库[关闭]
【发布时间】:2015-04-29 11:44:45
【问题描述】:

我正在寻找可以让我执行以下操作的库:

matches(
    user_input="hello world how are you what are you doing",
    keywords='+world -tigers "how are" -"bye bye"'
)

基本上我希望它根据单词的存在、单词的缺失和单词序列来匹配字符串。我不需要像 Solr 这样的搜索引擎,因为字符串不会提前知道,只会被搜索一次。这样的图书馆是否已经存在,如果存在,我在哪里可以找到它?还是我注定要创建一个正则表达式生成器?

【问题讨论】:

  • 试试 nltk.org。这就是python的自然语言处理库
  • 不确定要匹配的数据大小,但 Lucene/Solr 是更大规模应用程序的最佳选择 - lucene.apache.org/solr。另请查看pysolr
  • 我希望匹配非常少量的数据:100 个字以下的字符串,仅使用几个关键字的关键字规则。匹配完成后,我不再使用原始字符串,所以我认为 Solr 不是我需要的。我也不需要搜索模糊或特定语言。

标签: python parsing full-text-search negate


【解决方案1】:

regex module 支持命名列表:

import regex

def match_words(words, string):
    return regex.search(r"\b\L<words>\b", string, words=words)

def match(string, include_words, exclude_words):
    return (match_words(include_words, string) and
            not match_words(exclude_words, string))

例子:

if match("hello world how are you what are you doing",
         include_words=["world", "how are"],
         exclude_words=["tigers", "bye bye"]):
    print('matches')

您可以使用标准 re 模块来实现命名列表,例如:

import re

def match_words(words, string):
    re_words = '|'.join(map(re.escape, sorted(words, key=len, reverse=True)))
    return re.search(r"\b(?:{words})\b".format(words=re_words), string)

如何根据 +、- 和 "" 语法构建包含和排除的单词列表?

你可以使用shlex.split():

import shlex

include_words, exclude_words = [], []
for word in shlex.split('+world -tigers "how are" -"bye bye"'):
    (exclude_words if word.startswith('-') else include_words).append(word.lstrip('-+'))

print(include_words, exclude_words)
# -> (['world', 'how are'], ['tigers', 'bye bye'])

【讨论】:

  • 聪明而且可能比 Amrita 的解决方案更快,但我认为这对我的关键字语法也没有帮助,除非我在 re_words 创建中遗漏了一些魔法。
  • 我已经更新了答案,展示了如何使用 re_words 来实现 match() 函数以及如何解析 '+world -tigers "how are" -"bye bye"'
  • 完美。没有意识到 shlex 只会使用 split 函数来做到这一点。这是完美的!
【解决方案2】:

从您给出的示例中,您不需要正则表达式,除非您正在寻找单词中的模式/表达式..

    d="---your string ---"
    mylist= d.split()
    M=[]
    Excl=["---excluded words---"]
    for word in mylist:
        if word not in Excl:
            M.append(word)
    print M

您可以编写一个通用函数,它可以与任何字符串列表和排除列表一起使用。

【讨论】:

  • 当然可以,但是如何根据 +、- 和 "" 语法构建包含和排除单词的列表?是否有现成的解决方案,或者我必须使用 lex 来创建它?
  • “你不需要正则表达式” 但正则表达式有帮助。基于正则表达式的解决方案只查看字符串两次。您的解决方案查看len(mylist) 次,即~100 次。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-26
  • 2011-03-24
  • 1970-01-01
  • 2012-08-31
  • 2012-11-27
  • 1970-01-01
  • 2010-09-20
相关资源
最近更新 更多