编写代码实现从text.txt中返回满足用户输入任意关键词的匹配结果。
时间: 2024-05-03 16:21:16 浏览: 17
以下是一个Python代码示例:
```python
def search_text_file(keywords):
results = []
with open('text.txt', 'r') as f:
for line in f:
if any(keyword in line for keyword in keywords):
results.append(line.strip())
return results
```
该函数接受一个关键词列表作为参数,打开名为"text.txt"的文件,并逐行读取其中的内容。对于每一行,它使用Python的任意()函数来检查该行是否包含任何一个关键词。如果是,则将该行添加到结果列表中。最后,该函数返回结果列表。
例如,如果我们调用search_text_file(['Python', 'code']),它将返回包含"Python"或"code"关键词的所有行。如果"text.txt"文件包含以下内容:
```
Python is a popular programming language.
I love writing Python code.
This is an example of searching text file.
```
则该函数将返回以下结果:
```
['Python is a popular programming language.', 'I love writing Python code.']
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)