regex
模块支持命名列表:
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'])