Skip to main content
 首页 » 编程设计

python之如何将句子列表与关键字列表匹配

2024年12月31日9bjzhanghao

a我想制作一个新列表,将句子列表与关键字列表相匹配。

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') 中全部输入。有没有其他方法可以将句子列表与关键字列表相匹配。

请您参考如下方法:

您必须根据关键字列表检查每个字符串。使用列表理解,假设简单的字符串匹配就足够了(不需要正则表达式)。

matched_list = [ 
    string for string in lst if any( 
        keyword in string for keyword in keywords)] 

这实际上只是一种简洁的说法:

matched_list = [] 
for string in lst: 
    if any(keyword in string for keyword in keywords): 
        matched_list.append(string) 

any 将短路,为第一个匹配的关键字返回 True(如果没有找到匹配则返回 False)。


如果你想使用正则表达式,你可以预编译你的模式,然后像往常一样在循环中调用 pattern.search:

import re 
p = re.compile('|'.join(map(re.escape, keywords))) 
matched_list = [string for string in lst if p.search(string)]