我想做一个新的列表,从一个句子列表匹配关键字列表。你知道吗
list = ['This sentence contains disclosure.', 'This sentence contains none declared.', 'This sentence contains competing interest.', 'This sentence contains authors declare.']
keywords = ['disclosure ', 'none declared', 'interest']
新的名单应该是这样打印出来的
matched_list = ['This sentence contains disclosure.', 'This sentence contains none declared.']
我试过使用
r = re.compile('.*disclosure')
newlist = list(filter(r.match, list))
不过,我有一个非常大的关键字列表,不可能在r = re.compile('.*keywords')
中全部键入。有没有其他方法可以将一系列句子与一系列关键字进行匹配。你知道吗
您必须对照关键字列表检查每个字符串。使用列表理解,假设简单的字符串匹配就足够了(不需要regex)。你知道吗
这其实只是一个简洁的说法:
any
将短路,为匹配的第一个关键字返回True
(否则,如果找不到匹配项,则返回False
)。你知道吗如果要使用regex,可以预编译模式,然后像往常一样在循环中调用
pattern.search
:相关问题 更多 >
编程相关推荐