说在前面
使用llm输出了字符串内容后,需要对该输出进行处理,获取到里面某些内容,故在此记录下python如何使用正则表达式来截取字符串内容里面指定字段内容。
代码
import re
# 定义一个函数来提取llm输出内容的3个字段内容
def extract_field(field_name, text):
pattern = f"{field_name}: (.*?)(?=\n\n|$)"
match = re.search(pattern, text, re.DOTALL)
return match.group(1).strip() if match else None
if __name__ == "__main__":
text = """
Step1:
Summarization: 瀑布是当河流经过悬崖时产生的一种水流现象,其形成与悬崖密切相关。
Step2:
Question: 瀑布是否包含悬崖的一部分?
Step3:
Context: 瀑布是当河流经过悬崖时产生的一种水流现象,其形成与悬崖密切相关。
Question: 瀑布是否包含悬崖的一部分?
Answer: No.
"""
# 提取Summarization, Question, Answer字段
summarization = extract_field("Summarization", text)
question = extract_field("Question", text)
answer = extract_field("Answer", text)[:-1] # 忽略句尾符号
# 检查Answer是否为"yes",lower()转换为小写
if answer.lower() == "yes":
print("Answer is 'yes', saving it separately.")
# 这里可以添加代码来单独保存这个Answer
else:
print("Answer is not 'yes', no need to save it separately.")
# 这里可以添加其他处理逻辑
print("Summarization:", summarization)
print("Question:", question)
print("Answer:", answer)
截取效果
Summarization: 瀑布是当河流经过悬崖时产生的一种水流现象,其形成与悬崖密切相关。
Question: 瀑布是否包含悬崖的一部分?
Answer: No