首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python文本搜索库

Python文本搜索库
EN

Stack Overflow用户
提问于 2015-02-26 22:02:39
回答 2查看 2.3K关注 0票数 0

我正在寻找一个图书馆,它能让我做以下的事情:

代码语言:javascript
复制
matches(
    user_input="hello world how are you what are you doing",
    keywords='+world -tigers "how are" -"bye bye"'
)

基本上,我想要它匹配字符串的基础上存在的词,没有词和序列的词。我不需要一个搜索引擎一个la Solr,因为字符串不会事先知道,只会被搜索一次。这样的图书馆已经存在了吗?如果有的话,我会在哪里找到它呢?还是我注定要创建一个正则表达式生成器?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-02-27 00:20:12

module支持命名列表:

代码语言:javascript
复制
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))

示例:

代码语言:javascript
复制
if match("hello world how are you what are you doing",
         include_words=["world", "how are"],
         exclude_words=["tigers", "bye bye"]):
    print('matches')

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

代码语言:javascript
复制
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()

代码语言:javascript
复制
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'])
票数 2
EN

Stack Overflow用户

发布于 2015-02-27 00:52:15

从你给出的例子来看,你不需要Regex,除非你在寻找单词中的模式/表达式。

代码语言:javascript
复制
    d="---your string ---"
    mylist= d.split()
    M=[]
    Excl=["---excluded words---"]
    for word in mylist:
        if word not in Excl:
            M.append(word)
    print M

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28753623

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档