我正在寻找一个图书馆,它能让我做以下的事情:
matches(
user_input="hello world how are you what are you doing",
keywords='+world -tigers "how are" -"bye bye"'
)基本上,我想要它匹配字符串的基础上存在的词,没有词和序列的词。我不需要一个搜索引擎一个la Solr,因为字符串不会事先知道,只会被搜索一次。这样的图书馆已经存在了吗?如果有的话,我会在哪里找到它呢?还是我注定要创建一个正则表达式生成器?
发布于 2015-02-27 00:20:12
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'])发布于 2015-02-27 00:52:15
从你给出的例子来看,你不需要Regex,除非你在寻找单词中的模式/表达式。
d="---your string ---"
mylist= d.split()
M=[]
Excl=["---excluded words---"]
for word in mylist:
if word not in Excl:
M.append(word)
print M您可以编写一个泛型函数,它可以与任何字符串列表和排除列表一起使用。
https://stackoverflow.com/questions/28753623
复制相似问题