Skip to content

药物提取示例 🏥

LangExtract 擅长从临床文本中提取结构化医疗信息,特别适合医疗健康应用场景。

WARNING

免责声明: 本示例仅用于演示 LangExtract 的基础能力,不代表成熟或已批准的产品,不用于诊断或建议任何疾病的治疗,不应用于医疗建议。

基础命名实体识别 (NER)

以下示例展示 LangExtract 如何提取结构化药物信息:

python
import langextract as lx

# 输入文本
input_text = "患者服用布洛芬 400mg 口服 每4小时一次 连续两天。"

# 定义提取 prompt
prompt_description = "按照文本中出现的顺序提取药物信息,包括药物名称、剂量、给药途径、频率和持续时间。"

# 定义示例数据
examples = [
    lx.data.ExampleData(
        text="患者接受头孢唑林 250mg 静脉注射 每日三次 连续一周。",
        extractions=[
            lx.data.Extraction(extraction_class="dosage", extraction_text="250mg"),
            lx.data.Extraction(extraction_class="route", extraction_text="静脉注射"),
            lx.data.Extraction(extraction_class="medication", extraction_text="头孢唑林"),
            lx.data.Extraction(extraction_class="frequency", extraction_text="每日三次"),
            lx.data.Extraction(extraction_class="duration", extraction_text="连续一周")
        ]
    )
]

result = lx.extract(
    text_or_documents=input_text,
    prompt_description=prompt_description,
    examples=examples,
    model_id="gemini-2.5-pro",
)

# 显示提取结果
print(f"输入: {input_text}\n")
print("提取的实体:")
for entity in result.extractions:
    position_info = ""
    if entity.char_interval:
        start, end = entity.char_interval.start_pos, entity.char_interval.end_pos
        position_info = f" (位置: {start}-{end})"
    print(f"• {entity.extraction_class}: {entity.extraction_text}{position_info}")

# 保存并可视化结果
lx.io.save_annotated_documents([result], output_name="medical_ner_extraction.jsonl", output_dir=".")

# 生成交互式可视化
html_content = lx.visualize("medical_ner_extraction.jsonl")
with open("medical_ner_visualization.html", "w") as f:
    if hasattr(html_content, 'data'):
        f.write(html_content.data)
    else:
        f.write(html_content)

print("交互式可视化已保存至 medical_ner_visualization.html")

预期输出

输入: 患者服用布洛芬 400mg 口服 每4小时一次 连续两天。

提取的实体:
• medication: 布洛芬
• dosage: 400mg
• route: 口服
• frequency: 每4小时一次
• duration: 连续两天
交互式可视化已保存至 medical_ner_visualization.html

关系提取 (RE)

对于涉及实体间关系的更复杂提取,LangExtract 可以提取药物及其关联属性:

python
import langextract as lx

# 包含多个药物的文本
input_text = """
患者上个月被开具了利辛普利和二甲双胍处方。
他每天服用利辛普利 10mg 治疗高血压,但经常漏服
二甲双胍 500mg,该药应每日两次服用以控制糖尿病。
"""

# 定义提取 prompt
prompt_description = """
提取药物及其详细信息,使用属性来分组相关信息:

1. 按文本中出现的顺序提取实体
2. 每个实体必须有 'medication_group' 属性将其链接到对应药物
3. 同一药物的所有详细信息应共享相同的 medication_group 值
"""

# 定义示例数据
examples = [
    lx.data.ExampleData(
        text="患者每天服用阿司匹林 100mg 保护心脏,睡前服用辛伐他汀 20mg。",
        extractions=[
            lx.data.Extraction(
                extraction_class="medication",
                extraction_text="阿司匹林",
                attributes={"medication_group": "阿司匹林"}
            ),
            lx.data.Extraction(
                extraction_class="dosage",
                extraction_text="100mg",
                attributes={"medication_group": "阿司匹林"}
            ),
            lx.data.Extraction(
                extraction_class="frequency",
                extraction_text="每天",
                attributes={"medication_group": "阿司匹林"}
            ),
            lx.data.Extraction(
                extraction_class="condition",
                extraction_text="保护心脏",
                attributes={"medication_group": "阿司匹林"}
            ),
            lx.data.Extraction(
                extraction_class="medication",
                extraction_text="辛伐他汀",
                attributes={"medication_group": "辛伐他汀"}
            ),
            lx.data.Extraction(
                extraction_class="dosage",
                extraction_text="20mg",
                attributes={"medication_group": "辛伐他汀"}
            ),
            lx.data.Extraction(
                extraction_class="frequency",
                extraction_text="睡前",
                attributes={"medication_group": "辛伐他汀"}
            )
        ]
    )
]

result = lx.extract(
    text_or_documents=input_text,
    prompt_description=prompt_description,
    examples=examples,
    model_id="gemini-2.5-pro",
)

# 按药物分组显示
print("提取的药物:")
medication_groups = {}
for extraction in result.extractions:
    if extraction.attributes and "medication_group" in extraction.attributes:
        group_name = extraction.attributes["medication_group"]
        medication_groups.setdefault(group_name, []).append(extraction)

for med_name, extractions in medication_groups.items():
    print(f"\n* {med_name}")
    for extraction in extractions:
        print(f"  • {extraction.extraction_class}: {extraction.extraction_text}")

关键特性

  • 命名实体识别: 提取带类型的实体(药物、剂量、途径等)
  • 关系提取: 使用属性将相关实体分组
  • 位置追踪: 记录提取实体在源文本中的精确位置
  • 结构化输出: 以适合医疗应用的格式组织信息
  • 交互式可视化: 生成 HTML 可视化界面探索复杂的医疗提取结果

非官方指南。与 Google 无关。