如何将句子列表与关键字列表进行匹配

2024-09-29 02:27:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个新的列表,从一个句子列表匹配关键字列表。你知道吗

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')中全部键入。有没有其他方法可以将一系列句子与一系列关键字进行匹配。你知道吗


Tags: renone列表关键字thissentencelist句子
1条回答
网友
1楼 · 发布于 2024-09-29 02:27:44

您必须对照关键字列表检查每个字符串。使用列表理解,假设简单的字符串匹配就足够了(不需要regex)。你知道吗

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)。你知道吗


如果要使用regex,可以预编译模式,然后像往常一样在循环中调用pattern.search

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

相关问题 更多 >