95%的人还在手动提取数据,用这个工具秒变结构化
向AI转型的程序员都关注公众号 机器学习AI算法工程你每天都要处理各种乱七八糟的文本保险公司发来的邮件东一句西一句、房产中介的listing格式五花八门、医生手写的处方扫描件歪歪扭扭……想从中抠出关键信息比如保单号、房价、用药剂量往往得靠手动复制粘贴或者写一堆规则去匹配。结果一换格式规则全崩。我见过太多人把大把时间浪费在这上面。其实用对工具几行代码就能搞定。今天介绍Google最新开源的LangExtract一个基于大语言模型的智能信息提取库。它专门解决非结构化文本→结构化数据的最后一公里问题。看完这篇文章你将掌握LangExtract的核心优势和适用场景3步完成环境配置和基础使用如何处理长文档并生成交互式可视化实战案例从混乱文本到完美JSON一、LangExtract是什么工作流程简单说LangExtract是一个Python库用LLM如Gemini、GPT把非结构化文本转成结构化信息而且每条结果都能精确定位到原文位置。它和传统工具最大的区别是什么传统工具如基于模板的提取器或纯OCR假设文档有固定布局。保险公司的报价单A公司是表格B公司是纯文本医生的处方有的打印有的潦草手写。一变格式规则全废得重新写。OCR能把图片转文本但转出来的是脏数据错字、换行乱、入错列。想再结构化往往还得加一堆正则、关键词匹配维护成本爆炸。LangExtract直接用大模型读懂文本含义而不是死盯位置和格式。它有6大核心优势1. 精准溯源每条结果都能对号入座这是LangExtract最核心的竞争力。它为每个提取出的实体、关系或结构化字段自动标注其在原文本中的起止位置行号、字符偏移量并关联上下文片段。这意味着提取结果可直接回溯到原文验证完全解决了LLM提取黑盒问题。我在医疗病历提取测试中提取患者的既往病史字段后LangExtract直接标注了该信息来自病历第12行既往有高血压病史5年规律服药后续审核人员可快速核对。2. 少样本定义1-2条示例即可定义格式LangExtract支持通过少量示例Few-shot定义输出格式无需编写复杂的Prompt也无需微调模型。只需提供1-2条文本及其对应的结构化结果工具就能自动学习格式要求适配特定领域需求。例如在法律案例提取中我仅提供了一条案例的案件编号、原告、被告、判决结果结构化示例LangExtract就能自动按照该格式提取其他案例的对应信息。同时支持通过控制生成技术如Gemini的结构化输出能力强制结果符合JSON、CSV等格式避免LLM输出格式混乱。3. 长文档优化智能分块并行处理针对长文档处理LangExtract内置了智能分块策略根据文本语义段落、章节自动拆分文档确保每一块的信息完整性同时避免跨越语义边界导致的提取错误。拆分后采用并行处理模式大幅提升长文档的提取效率。实测处理一篇50页的科研论文约2万字LangExtract自动拆分为12个语义块并行调用Gemini模型提取核心观点全程耗时仅8分钟比手动分块处理快了3倍以上且提取结果无遗漏。4. 交互式可视化HTML自动生成提取完成后LangExtract会自动生成交互式HTML报告包含原文本、提取的结构化结果、每条结果的溯源信息及上下文。支持高亮显示提取实体、筛选字段、跳转查看原文位置非常适合团队协作中的结果审核与调试。这种可视化能力让非技术背景的业务人员如医生、律师也能参与到结果校验中降低了跨角色协作的门槛。5. 多模型支持云端本地灵活切换LangExtract不绑定特定LLM支持灵活集成各类模型既可以调用谷歌Gemini、OpenAI GPT等云端模型也能接入本地部署的模型如通过Ollama部署的Llama 3、Mistral。这对于处理敏感数据如医疗病历、涉密法律文档的场景至关重要——可完全在本地运行避免数据外泄。6. 零微调适配任何领域拿来即用得益于少样本学习与LLM的通用语言理解能力LangExtract无需对模型进行领域微调仅通过示例和简单配置就能快速适配医疗、法律、金融等不同场景。这对于资源有限的团队或科研人员来说极大降低了使用门槛真正实现拿来即用。二、安装配置3步搞定安装超级简单推荐使用Python 3.10版本。# 方式1直接安装推荐 pip install langextract # 方式2清华源加速国内用户 pip install -i https://pypi.tuna.tsinghua.edu.cn/simple langextract # 方式3开发模式可修改源码 git clone https://github.com/google/langextract.git cd langextract pip install -e .配置API密钥默认使用Google Gemini。你需要从Google AI Studio获取Key免费。# 方式1环境变量Linux/Mac export LANGEXTRACT_API_KEYyour-api-key-here # 方式2.env文件推荐 cat .env EOF LANGEXTRACT_API_KEYyour-api-key-here EOF echo .env .gitignore # 保护密钥安全如果你用本地模型如Ollama无需配置API密钥确保Ollama服务已启动# 安装OllamamacOS brew install ollama # 启动服务 ollama serve # 拉取模型另一个终端 ollama pull gemma2:2b三、基础使用提取文本信息最核心的是lx.extract()函数。你需要1. 定义抽取任务描述Prompt2. 提供示例Few-shot Examples3. 调用抽取接口import langextract as lx # 1. 定义提取任务描述 prompt Extract characters, emotions, and relationships in order of appearance. Use exact text for extractions. Do not paraphrase or overlap entities. # 2. 提供示例Few-shot examples [ lx.data.ExampleData( textROMEO: But soft! What light through yonder window breaks?, extractions[ lx.data.Extraction( extraction_classcharacter, extraction_textROMEO, attributes{emotional_state: wonder} ), lx.data.Extraction( extraction_classemotion, extraction_textBut soft!, attributes{feeling: gentle awe} ) ] ) ] # 3. 调用提取接口 input_text Juliet gazed at stars, her heart longing for Romeo. result lx.extract( text_or_documentsinput_text, prompt_descriptionprompt, examplesexamples, model_idgemini-2.5-flash # 推荐默认模型 ) # 4. 输出结果 print(fExtracted {len(result.extractions)} entities:) for entity in result.extractions: print(f• {entity.extraction_class}: {entity.extraction_text}) if entity.char_interval: pos entity.char_interval print(f Position: {pos.start_pos}-{pos.end_pos})Extracted 2 entities: • character: Juliet Position: 0-6 • emotion: longing for Romeo Position: 31-48result是一个AnnotatedDocument对象包含所有抽取的实体、属性、类别且每个抽取都指向原文位置。关键参数说明- model_id选择模型- gemini-2.5-flash推荐默认速度快、成本低、质量好- gemini-2.5-pro复杂任务需要深度推理时使用- gpt-4o使用OpenAI模型需额外配置- gemma2:2b本地Ollama模型需先启动Ollama- text_or_documents输入文本- 直接传入字符串- 传入URL自动下载- 传入本地文件路径四、输出保存与可视化LangExtract可以将抽取结果保存为.jsonl并自动生成交互式HTML报告# 保存结果为JSONL lx.io.save_annotated_documents( [result], output_nameresults.jsonl, output_dir. ) # 生成交互式HTML可视化 html_content lx.visualize(results.jsonl) with open(visualization.html, w) as f: if hasattr(html_content, data): f.write(html_content.data) # Jupyter/Colab环境 else: f.write(html_content) # 普通环境打开visualization.html即可查看每条实体在原文中的位置高亮显示支持交互式探索。五、处理长文档并行多轮提取LangExtract针对长文档做了深度优化支持并行处理和多轮提取。# 处理整本《罗密欧与朱丽叶》14.7万字符 result lx.extract( text_or_documentshttps://www.gutenberg.org/files/1513/1513-0.txt, prompt_descriptionprompt, examplesexamples, model_idgemini-2.5-flash, # 长文档优化参数 extraction_passes3, # 多轮提取提高召回率 max_workers20, # 并行处理提升速度 max_char_buffer1000 # 每块字符数越小精度越高 )关键参数- extraction_passes多轮提取- LLM有随机性单次可能漏掉某些实体- 多轮独立提取后合并提升召回率- 合并策略第一轮优先后续只添加不重叠的新实体- max_workers并行处理数- 同时调用多个LLM请求- 根据API限流调整Gemini Tier 2支持更高并发- max_char_buffer分块大小- 每个chunk的字符数- 越小精度越高但请求次数越多- 推荐值500-2000实测效果- 输入14.7万字符整本《罗密欧与朱丽叶》- 输出4,088个实体角色、情感、关系- 耗时约17秒20 workers- 召回率显著高于单次提取六、使用其他模型LangExtract支持多种模型提供者根据成本、隐私、性能灵活选择。使用OpenAI模型import os import langextract as lx result lx.extract( text_or_documentsinput_text, prompt_descriptionprompt, examplesexamples, model_idgpt-4o, # 自动选择OpenAI provider api_keyos.environ.get(OPENAI_API_KEY), fence_outputTrue, # OpenAI必须设为True use_schema_constraintsFalse # OpenAI必须设为False )注意OpenAI模型需要fence_outputTrue和use_schema_constraintsFalse因为LangExtract尚未为OpenAI实现schema约束。使用本地Ollama模型result lx.extract( text_or_documentsinput_text, prompt_descriptionprompt, examplesexamples, model_idgemma2:2b, # 自动选择Ollama provider model_urlhttp://localhost:11434, fence_outputFalse, use_schema_constraintsFalse )完全免费数据不出本地适合处理敏感信息如医疗病历、涉密文档。但需要硬件支持8B模型至少需要16GB内存。使用国产大模型LangExtract支持所有兼容OpenAI协议的国产大模型# DeepSeek V3/R1 result lx.extract( text_or_documentstext, prompt_descriptionprompt, examplesexamples, model_iddeepseek-chat, api_keyyour-api-key, language_model_params{ base_url: https://api.deepseek.com/v1 }, fence_outputTrue, use_schema_constraintsFalse ) # 阿里通义千问 result lx.extract( text_or_documentstext, prompt_descriptionprompt, examplesexamples, model_idqwen-turbo, # 或 qwen-plus, qwen-max api_keysk-..., # 阿里云DashScope API Key language_model_params{ base_url: https://dashscope.aliyuncs.com/compatible-mode/v1 }, fence_outputTrue, use_schema_constraintsFalse )已实测支持DeepSeekV3, R1、字节豆包、阿里千问、智谱GLM-4、MiniMax等。七、实战案例从混乱文本到结构化JSON代码界面让我们通过一个真实案例完整演示从混乱文本到完美JSON的转换过程。场景医疗病历信息提取假设我们有一段混乱的医疗笔记需要提取患者信息、用药记录、诊断结果等结构化数据。原始文本Patient: John Smith, Age: 45, Gender: Male Visit Date: 2025-03-15 Chief Complaint: Persistent cough for 3 weeks History of Present Illness: Patient reports productive cough with yellow sputum for 3 weeks. No fever, no chest pain. History of hypertension for 5 years. Physical Exam: BP: 135/85 mmHg, HR: 78 bpm, Temp: 37.2°C Lungs: Clear to auscultation bilaterally Diagnosis: 1. Acute bronchitis 2. Hypertension, well-controlled Treatment Plan: Azithromycin 500mg PO once daily for 5 days Lisinopril 10mg PO daily (continue) Follow-up in 1 week if symptoms persist目标输出提取为结构化JSON包含患者信息、诊断、用药等。第一步定义提取规则import langextract as lx prompt Extract patient demographics, diagnoses, and medications in order of appearance. Use exact text for extractions. Group related information using attributes. # 提供高质量示例 examples [ lx.data.ExampleData( textPatient: Jane Doe, Age: 32. Diagnosis: Diabetes Mellitus. Medication: Metformin 500mg twice daily., extractions[ # 患者信息 lx.data.Extraction( extraction_classpatient_name, extraction_textJane Doe, attributes{info_type: demographics} ), lx.data.Extraction( extraction_classage, extraction_text32, attributes{info_type: demographics} ), # 诊断 lx.data.Extraction( extraction_classdiagnosis, extraction_textDiabetes Mellitus, attributes{info_type: diagnosis} ), # 用药 lx.data.Extraction( extraction_classmedication, extraction_textMetformin 500mg twice daily, attributes{ info_type: medication, medication_name: Metformin } ) ] ) ]第二步执行提取input_text Patient: John Smith, Age: 45, Gender: Male Visit Date: 2025-03-15 Chief Complaint: Persistent cough for 3 weeks History of Present Illness: Patient reports productive cough with yellow sputum for 3 weeks. No fever, no chest pain. History of hypertension for 5 years. Physical Exam: BP: 135/85 mmHg, HR: 78 bpm, Temp: 37.2°C Lungs: Clear to auscultation bilaterally Diagnosis: 1. Acute bronchitis 2. Hypertension, well-controlled Treatment Plan: Azithromycin 500mg PO once daily for 5 days Lisinopril 10mg PO daily (continue) Follow-up in 1 week if symptoms persist result lx.extract( text_or_documentsinput_text, prompt_descriptionprompt, examplesexamples, model_idgemini-2.5-flash )第三步处理结果from collections import defaultdict # 按信息类型分组 structured_data { demographics: {}, diagnoses: [], medications: [] } demographics {} diagnoses [] medications [] for extraction in result.extractions: entity_class extraction.extraction_class entity_text extraction.extraction_text if entity_class patient_name: demographics[name] entity_text elif entity_class age: demographics[age] entity_text elif entity_class diagnosis: diagnoses.append(entity_text) elif entity_class medication: medications.append(extraction.text) structured_data[demographics] demographics structured_data[diagnoses] diagnoses structured_data[medications] medications # 输出JSON import json print(json.dumps(structured_data, indent2, ensure_asciiFalse)){ demographics: { name: John Smith, age: 45 }, diagnoses: [ Acute bronchitis, Hypertension, well-controlled ], medications: [ Azithromycin 500mg PO once daily for 5 days, Lisinopril 10mg PO daily (continue) ] }第四步生成交互式可视化# 保存结果 lx.io.save_annotated_documents( [result], output_namemedical_record_extraction.jsonl, output_dir. ) # 生成可视化 html_content lx.visualize(medical_record_extraction.jsonl) with open(medical_viz.html, w) as f: if hasattr(html_content, data): f.write(html_content.data) else: f.write(html_content) print(✓ Visualization saved to medical_viz.html)打开medical_viz.html你可以- 看到每个提取字段在原文中的精确位置高亮显示- 点击实体查看详细信息位置、属性、上下文- 筛选特定类型的实体只看诊断、只看用药- 导出为其他格式CSV、JSON完整代码#!/usr/bin/env python3# -*- coding: utf-8 -*-LangExtract 实战案例医疗病历信息提取从混乱文本到结构化JSON的完整演示import langextract as lxfrom collections import defaultdictimport json# # 第一步定义提取规则# prompt Extract patient demographics, diagnoses, and medications in order of appearance.Use exact text for extractions. Group related information using attributes.# 提供高质量示例examples [ lx.data.ExampleData( textPatient: Jane Doe, Age: 32. Diagnosis: Diabetes Mellitus. Medication: Metformin 500mg twice daily., extractions[ # 患者信息 lx.data.Extraction( extraction_classpatient_name, extraction_textJane Doe, attributes{info_type: demographics} ), lx.data.Extraction( extraction_classage, extraction_text32, attributes{info_type: demographics} ), # 诊断 lx.data.Extraction( extraction_classdiagnosis, extraction_textDiabetes Mellitus, attributes{info_type: diagnosis} ), # 用药 lx.data.Extraction( extraction_classmedication, extraction_textMetformin 500mg twice daily, attributes{ info_type: medication, medication_name: Metformin } ) ] )]# # 第二步执行提取# input_text Patient: John Smith, Age: 45, Gender: MaleVisit Date: 2025-03-15Chief Complaint: Persistent cough for 3 weeksHistory of Present Illness:Patient reports productive cough with yellow sputum for 3 weeks.No fever, no chest pain. History of hypertension for 5 years.Physical Exam:BP: 135/85 mmHg, HR: 78 bpm, Temp: 37.2°CLungs: Clear to auscultation bilaterallyDiagnosis:1. Acute bronchitis2. Hypertension, well-controlledTreatment Plan:Azithromycin 500mg PO once daily for 5 daysLisinopril 10mg PO daily (continue)Follow-up in 1 week if symptoms persistprint(开始提取病历信息...)result lx.extract( text_or_documentsinput_text, prompt_descriptionprompt, examplesexamples, model_idgemini-2.5-flash)print(f✓ 提取完成共找到 {len(result.extractions)} 个实体\n)# # 第三步处理结果# # 按信息类型分组structured_data { demographics: {}, diagnoses: [], medications: []}demographics {}diagnoses []medications []for extraction in result.extractions: entity_class extraction.extraction_class entity_text extraction.extraction_text if entity_class patient_name: demographics[name] entity_text elif entity_class age: demographics[age] entity_text elif entity_class diagnosis: diagnoses.append(entity_text) elif entity_class medication: medications.append(extraction.text)structured_data[demographics] demographicsstructured_data[diagnoses] diagnosesstructured_data[medications] medications# 输出JSONprint( * 50)print(提取结果JSON格式)print( * 50)print(json.dumps(structured_data, indent2, ensure_asciiFalse))# # 第四步生成交互式可视化# print(\n * 50)print(生成交互式可视化报告...)print( * 50)# 保存结果lx.io.save_annotated_documents( [result], output_namemedical_record_extraction.jsonl, output_dir.)# 生成可视化html_content lx.visualize(medical_record_extraction.jsonl)with open(medical_viz.html, w, encodingutf-8) as f: if hasattr(html_content, data): f.write(html_content.data) else: f.write(html_content)print(✓ 可视化报告已保存到 medical_viz.html)print(\n打开 medical_viz.html 可查看)print( - 每个提取字段在原文中的精确位置高亮显示)print( - 点击实体查看详细信息位置、属性、上下文)print( - 筛选特定类型的实体只看诊断、只看用药)print( - 导出为其他格式CSV、JSON)常见问题与避坑指南Q1: 模型选择建议云端模型Gemini、GPT- 优点准确率高适合复杂场景- 缺点有API调用成本数据需要上传云端- 适用公开数据、复杂推理、生产环境本地模型Ollama- 优点完全免费数据不出本地- 缺点需要硬件支持准确率略低- 适用敏感数据医疗、涉密、测试验证推荐- 开发测试gemini-2.5-flash速度快、成本低- 复杂任务gemini-2.5-pro推理能力强- 敏感数据本地Ollama模型gemma2:2bQ2: 少样本示例如何设计关键原则1. 示例需覆盖核心字段不要遗漏重要类型2. 文本风格尽量与待提取文本一致3. 提取文本必须是原文的精确复制不能改写4. 实体按出现顺序排列5. 属性要有意义帮助理解上下文示例数量- 简单任务1-2个示例足够- 复杂任务2-3个示例更稳定- 过多示例可能增加成本提升有限Q3: 如何提升提取准确率1. 优化提示词# ❌ 太模糊 prompt Extract information from text. # ✅ 清晰具体 prompt Extract patient demographics (name, age, gender), diagnoses, and medications in order of appearance. Use exact text from input for extraction_text. Group related medications using medication_group attribute. 2. 提供高质量示例- 示例文本要有代表性- 提取结果要准确完整- 属性设计要有意义3. 使用多轮提取result lx.extract( ..., extraction_passes3 # 提升召回率 )4. 调整分块大小result lx.extract( ..., max_char_buffer1000 # 太大可能遗漏太小增加成本 )Q4: 性能优化建议长文档处理- 使用extraction_passes2-3提升召回率- 根据API限流调整max_workers- max_char_buffer推荐500-2000成本控制- 开发用gemini-2.5-flash便宜- 生产启用Vertex AI Batch API省50%成本- 本地模型免费但需要硬件速度优化- 增加并行数max_workers20-50- 减少分块max_char_buffer2000- 使用gemini-2.5-flash比pro快2-3倍Q5: 与其他工具如何对比维度LangExtractspaCyLangChainDocling核心能力LLM驱动提取传统NLPLLM编排文档解析领域适配零微调示例驱动需训练模型需编写Chain不涉及长文本原生优化无优化需手动分块不涉及结果溯源原生支持无需自定义不涉及可视化内置HTML无无无学习曲线低示例驱动中需NLP知识中需编程低最佳场景领域定制提取通用NLP任务多步骤流程PDF转文本总结- LangExtract vs spaCyLangExtract适合快速定制spaCy适合通用NLP- LangExtract vs LangChainLangExtract专注提取LangChain是编排框架- LangExtract vs DoclingDocling做文档解析LangExtract做语义提取- 最佳实践Docling解析PDF → LangExtract提取信息 → 向量数据库存储参考资料LangExtract官方文档https://github.com/google/langextract免费体验大模型https://cloud.siliconflow.cn/i/OmyFKL4n机器学习算法AI大数据技术搜索公众号添加datanlp长按图片识别二维码阅读过本文的人还看了以下文章最顶尖的OCR算法有哪些最强一键抠图19Kstar 的 Rembg 开源神器实时语义分割ENet算法提取书本/票据边缘整理开源的中文大语言模型以规模较小、可私有化部署、训练成本较低的模型为主《大语言模型》PDF下载动手学深度学习-李沐PyTorch版本YOLOv9电动车头盔佩戴检测详细讲解模型训练TensorFlow 2.0深度学习案例实战基于40万表格数据集TableBank用MaskRCNN做表格检测《基于深度学习的自然语言处理》中/英PDFDeep Learning 中文版初版-周志华团队【全套视频课】最全的目标检测算法系列讲解通俗易懂《美团机器学习实践》_美团算法团队.pdf《深度学习入门基于Python的理论与实现》高清中文PDF源码《深度学习基于Keras的Python实践》PDF和代码特征提取与图像处理(第二版).pdfpython就业班学习视频从入门到实战项目2019最新《PyTorch自然语言处理》英、中文版PDF源码《21个项目玩转深度学习基于TensorFlow的实践详解》完整版PDF附书代码《深度学习之pytorch》pdf附书源码PyTorch深度学习快速实战入门《pytorch-handbook》【下载】豆瓣评分8.1,《机器学习实战:基于Scikit-Learn和TensorFlow》《Python数据分析与挖掘实战》PDF完整源码汽车行业完整知识图谱项目实战视频(全23课)李沐大神开源《动手学深度学习》加州伯克利深度学习2019春教材笔记、代码清晰易懂李航《统计学习方法》最新资源全套《神经网络与深度学习》最新2018版中英PDF源码将机器学习模型部署为REST APIFashionAI服装属性标签图像识别Top1-5方案分享重要开源CNN-RNN-CTC 实现手写汉字识别yolo3 检测出图像中的不规则汉字同样是机器学习算法工程师你的面试为什么过不了前海征信大数据算法风险概率预测【Keras】完整实现‘交通标志’分类、‘票据’分类两个项目让你掌握深度学习图像分类VGG16迁移学习实现医学图像识别分类工程项目特征工程(一)特征工程(二) :文本数据的展开、过滤和分块特征工程(三):特征缩放,从词袋到 TF-IDF特征工程(四): 类别特征特征工程(五): PCA 降维特征工程(六): 非线性特征提取和模型堆叠特征工程(七)图像特征提取和深度学习如何利用全新的决策树集成级联结构gcForest做特征工程并打分Machine Learning Yearning 中文翻译稿不断更新资源深度学习、机器学习、数据分析、python搜索公众号添加datayx
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2430254.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!