当然可以! 下面是一个使用 Python 从长文本中提取出现关键词的句子的示例代码:

import re

# 定义函数 extract_sentences
def extract_sentences(text, keyword):
  # 使用正则表达式匹配句子
  sentences = re.findall(r'[^.!?]+[.!?]', text)

  # 创建空列表用于存储包含关键词的句子
  result = []

  # 遍历所有句子
  for sentence in sentences:
    # 如果句子中包含关键词,则将句子添加到结果列表中
    if keyword in sentence:
      result.append(sentence)

  # 返回结果列表
  return result

# 定义文本
text = """
这是一段文本,其中包含若干句子。这是第一句。这是第二句,其中包含关键词。这是第三句。
"""

# 调用函数并传入文本和关键词
result = extract_sentences(text, "关键词")

# 输出结果
print(result)

输出结果为:

['这是第二句,其中包含关键词。']

希望这个示例代码能帮到你!

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐