python - 在 List of Sentences 中查找单词列表并返回匹配的句子
问题描述
从句子列表和单词列表中,如何返回句子列表,前提是所有三个单词都与单词列表(Trigrams)匹配。
请建议。以下是示例列表。
listwords = [['people','suffering','acute'], ['Covid-19','Corona','like'], ['people','must','collectively']]
listsent = ['The number of people suffering acute hunger could almost double.',
'Lockdowns and global economic recession have',
'one more shock – like Covid-19 – to push them over the edge',
'people must collectively act now to mitigate the impact']
输出列表应该是第一个和最后一个句子,因为它们在 listwords 中有三个匹配的单词。
预期输出为:
['The number of people suffering acute hunger could almost double.',
'people must collectively act now to mitigate the impact']
解决方案
欢迎来到堆栈溢出
试试这个解决方案:
listwords = [['people','suffering','acute'], ['Covid-19','Corona','like'], ['people','must','collectively']]
listsent = ['The number of people suffering acute hunger could almost double.',
'Lockdowns and global economic recession have',
'one more shock – like Covid-19 – to push them over the edge',
'people must collectively act now to mitigate the impact']
# interate through each sentence
for sentence in listsent:
# iterate through each group of words
for words in listwords:
# check to see if each word group is in the current sentence
if all(word in sentence for word in words):
print(sentence)
我评论了这些台词,让您了解发生了什么
代码的第一部分遍历列表中的每个句子
for sentence in listsent:
然后我们需要遍历单词列表中的单词组
for words in listwords
这就是事情变得有趣的地方。由于您有嵌套列表,我们需要检查以确保在句子中找到所有三个单词
if all(word in sentence for word in words):
最后,您可以打印出包含所有单词的每个句子
print(sentence)
你也可以把它放在一个函数中,并将找到的句子作为一个新列表返回
listwords = [['people','suffering','acute'], ['Covid-19','Corona','like'], ['people','must','collectively']]
listsent = ['The number of people suffering acute hunger could almost double.',
'Lockdowns and global economic recession have',
'one more shock – like Covid-19 – to push them over the edge',
'people must collectively act now to mitigate the impact']
def check_words(listwords, listsent):
listsent_new = []
# interate through each sentence
for sentence in listsent:
# iterate through each group of words
for words in listwords:
# check to see if each word group is in the current sentence
if all(word in sentence for word in words):
listsent_new.append(sentence)
return listsent_new
if __name__ == '__main__':
print(check_words(listwords, listsent))
推荐阅读
- sql - Access/SQL:如何检查表中所有重复项(同一日期)的值是否为 0,除了一个?
- javascript - 如何在 MongoDB/Mongoose 文档数组中找到重复次数最多的值?
- android - FLAG_WINDOW_IS_OBSCURED 不适用于较新的 android
- reactjs - 尝试在 React JS 获取 JSX 表达式的函数中添加循环必须有一个父元素
- javascript - 类型 'Query' 不可分配给类型 '[(options?: QueryLazyOptions
在 codegen 的帮助下,我生成了自定义的 graphql 钩子和类型。
query loadUsers($where: UserFilter) { users(where: $where) { nodes { id email f
- azure - 如何为用户关闭 Azure 服务通知?
- javascript - 并行运行for循环
- python - 确定一个数字的词性
- identityserver4 - 身份服务器 /connect/token 给出空 500 错误 - 我如何找到错误消息?
- kubernetes - AWS EKS 服务账户集群角色绑定无法正常访问禁止访问