赞
踩
好的,我们可以使用 Python 中的正则表达式来解决这个问题。
首先,我们可以使用 Python 的 re
模块来匹配文本中的关键词。我们可以使用 re.finditer
方法来在文本中查找所有匹配的句子,然后将这些句子保存到一个列表中。
代码示例如下:
- import re# 关键词列表
- keywords = ['keyword1', 'keyword2', 'keyword3']
-
- # 将关键词列表转换为正则表达式
- pattern = '|'.join(keywords)
-
- # 读取文本文件
- with open('input.txt', 'r') as f:
- text = f.read()
-
- # 查找所有包含关键词的句子
- sentences = []
- for match in re.finditer(pattern, text):
- start = match.start()
- end = match.end()
- sentence = text[start:end]
- sentences.append(sentence)
-
- # 将结果保存到输出文件中
- with open('output.txt', 'w') as f:
- for sentence in sentences:
- f.write(sentence + '\n')

这段代码会读取 input.txt
文件中的文本,在文本中查找所有包含关键词的句子,然后将这些句子保存到 output.txt
文件中。
希望这些信息对你有帮助。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。