当前位置:   article > 正文

抽取txt文件中含有多个关键词的句子,并保存到txt文本中,直接写代码

python如何在txt寻找多个关键词

好的,我们可以使用 Python 中的正则表达式来解决这个问题。

首先,我们可以使用 Python 的 re 模块来匹配文本中的关键词。我们可以使用 re.finditer 方法来在文本中查找所有匹配的句子,然后将这些句子保存到一个列表中。

代码示例如下:

  1. import re# 关键词列表
  2. keywords = ['keyword1', 'keyword2', 'keyword3']
  3. # 将关键词列表转换为正则表达式
  4. pattern = '|'.join(keywords)
  5. # 读取文本文件
  6. with open('input.txt', 'r') as f:
  7. text = f.read()
  8. # 查找所有包含关键词的句子
  9. sentences = []
  10. for match in re.finditer(pattern, text):
  11. start = match.start()
  12. end = match.end()
  13. sentence = text[start:end]
  14. sentences.append(sentence)
  15. # 将结果保存到输出文件中
  16. with open('output.txt', 'w') as f:
  17. for sentence in sentences:
  18. f.write(sentence + '\n')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

这段代码会读取 input.txt 文件中的文本,在文本中查找所有包含关键词的句子,然后将这些句子保存到 output.txt 文件中。

希望这些信息对你有帮助。

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号