定义函数check( sentences, words), 其中sentences为包含若干句子的列表,words是包含若干关键字的列表。 函数功能为在sentences中找出包含至少一个words中关键词的句子,并构成列表。 提示:利用列表解析式、生成器表达式、串统计函数;
时间: 2024-10-28 16:15:29 浏览: 19
您可以定义`check`函数如下,它会遍历每个句子并检查是否包含任何一个关键字,如果满足条件,则将该句子添加到结果列表中:
```python
def check(sentences, words):
# 利用列表解析式匹配含有关键字的句子
matched_sentences = [sentence for sentence in sentences if any(word in sentence for word in words)]
return matched_sentences
```
或者,如果您想使用生成器表达式,可以稍微调整一下语法:
```python
def check(sentences, words):
matched_sentences = (sentence for sentence in sentences if any(word in sentence for word in words))
return list(matched_sentences) # 将生成器转换为列表返回
```
如果需要更细致的统计,比如每个句子包含的关键字数量,可以用以下方式:
```python
def check(sentences, words, count=False):
matched_sentences = [(sentence, sum((word in sentence) for word in words)) for sentence in sentences if any(word in sentence for word in words)]
if not count:
return [sentence for sentence, _ in matched_sentences]
else:
return matched_sentences
```
在这个版本里,`count=True`时,函数还会返回每个匹配句子及其包含的关键字数量的元组列表。
阅读全文