微信扫码
添加专属顾问
多年来,正则表达式一直是我解析文档的首选工具,我相信对于许多技术人员和行业也是如此。尽管正则表达式在某些情况下非常强大,但它们常常在面对真实世界文档的复杂性和多样性时缺少灵活性。
另一方面,大型语言模型提供了一种更强大、更灵活的方法来处理多种类型的文档结构和内容类型。
下面是一个常用的文档解析流程。为了简化问题,我们以研究论文处理的场景为例。
正则表达式(Regex)在处理研究论文结构的复杂性时存在显著的局限性,下面深入比较下这两种方法:
1、文档结构的灵活性
Regex 需要每个文档结构的特定模式,并且当给定文档偏离预期格式时会失败。LLMs自动理解并适应各种文档结构,并且无论相关信息位于文档中的哪个位置,它们都能够识别相关信息。2. 上下文理解
Regex 在不了解上下文或含义的情况下匹配模式。LLMs 对每个文档的含义有更细致的了解,这使他们能够更准确地提取相关信息。3. 维护和可扩展性
Regex随着文档格式的变化需要不断更新。添加对新信息类型的支持需要编写全新的正则表达式。LLMs 可以轻松适应新的文档类型,只需对初始提示进行最小的更改,这使得它们更具可扩展性。上述理由足以采用 LLMs 来解析研究论文等复杂文档。
实验文档来自于
本节提供了利用大型语言模型构建现实世界文档解析系统的所有步骤,你可以直接在本地运行。
project | |---Extract_Metadata_With_Large_Language_Models.ipynb |data | |---- extracted_metadata/ |---- 1706.03762v7.pdf |---- 1810.04805.pdf |---- prompts | |------ scientific_papers_prompt.txt
project 文件夹是根文件夹,包含 data 文件夹和notebookdata文件夹中有两个文件夹,extracted_metadata和prompts,以及两篇论文。extracted_metadata 当前为空,将包含 json 文件prompts文件夹中有文本格式的提示我们首先需要对需要提取的属性有一个明确的目标,为了简单起见,让我们重点关注我们场景的六个属性。
然后使用这些属性来定义提示,该提示清楚地解释了每个属性的含义以及最终输出的格式。文档的成功解析依赖于清晰解释每个属性含义以及以哪种格式提取最终结果的提示。
Scientific research paper:---{document}---You are an expert in analyzing scientific research papers. Please carefully read the provided research paper above and extract the following key information:Extract these six (6) properties from the research paper:- Paper Title: The full title of the research paper- Publication Year: The year the paper was published- Authors: The full names of all authors of the paper- Author Contact: A list of dictionaries, where each dictionary contains the following keys for each author:- Name: The full name of the author- Institution: The institutional affiliation of the author- Email: The email address of the author (if provided)- Abstract: The full text of the paper's abstract- Summary Abstract: A concise summary of the abstract in 2-3 sentences, highlighting the key pointsGuidelines:- The extracted information should be factual and accurate to the document.- Be extremely concise, except for the Abstract which should be copied in full.- The extracted entities should be self-contained and easily understood without the rest of the paper.- If any property is missing from the paper, please leave the field empty rather than guessing.- For the Summary Abstract, focus on the main objectives, methods, and key findings of the research.- For Author Contact, create an entry for each author, even if some information is missing. If an email or institution is not provided for an author, leave that field empty in the dictionary.Answer in JSON format. The JSON should contain 6 keys: "PaperTitle", "PublicationYear", "Authors", "AuthorContact", "Abstract", and "SummaryAbstract". The "AuthorContact" should be a list of dictionaries as described above.
Prompt中有6大块内容,下面是对这6部分内容进行详细解释。
1、文档占位符
Scientific research paper:---{document}---使用 {} 符号定义,它指示将包含文档全文以供分析的位置。2、角色指定
该模型被指定了一个角色,以便更好地执行任务,这在以下行中进行了定义,设置上下文并指示人工智能成为科学研究论文分析的专家。
You are an expert in analyzing scientific research papers.
3、提取指令
本节指定应从文档中提取的信息片段。
Extract these six (6) properties from the research paper:
4. 属性定义
此处定义了上述每个属性,其中包含要包含的信息及其格式策略的具体详细信息。例如,Author Contact 是包含其他详细信息的字典列表。
5、指导方针
这些指南告诉人工智能在提取过程中要遵循的规则,例如保持准确性以及如何处理丢失的信息。
6. 预期输出格式
这是最后一步,它指定回答时要考虑的确切格式,即 json 。
Answer in JSON format. The JSON should contain 6 keys: ...
现在让我们开始安装必要的库。我们的文档解析系统是由多个库构建的,每个组件的主要库如下所示:
pdfminer.six 、 PyPDF2 和 poppler-utils 用于处理各种 PDF 格式和结构。unstructured 及其依赖包(unstructured-inference 、 unstructured-pytesseract )用于从文档中智能提取内容。tesseract-ocr 用于识别图像或扫描文档中的文本。pillow-heif 用于图像处理任务。openai 库,用于在信息提取过程中利用 GPT 模型。%%bashpip -qqq install pdfminer.sixpip -qqq install pillow-heif==0.3.2pip -qqq install matplotlibpip -qqq install unstructured-inferencepip -qqq install unstructured-pytesseractpip -qqq install tesseract-ocrpip -qqq install unstructuredpip -qqq install openaipip -qqq install PyPDF2apt install -V tesseract-ocrapt install -V libtesseract-devsudo apt-get updateapt-get install -V poppler-utils
安装成功后,导入如下:
import osimport reimport jsonimport openaifrom pathlib import Pathfrom openai import OpenAIfrom PyPDF2 import PdfReaderfrom google.colab import userdatafrom unstructured.partition.pdf import partition_pdffrom tenacity import retry, wait_random_exponential, stop_after_attempt
在深入研究核心功能之前,我们需要使用必要的 API 凭据设置环境。
OPENAI_API_KEY = userdata.get('OPEN_AI_KEY')model_ID = userdata.get('GPT_MODEL')os.environ["OPENAI_API_KEY"] = OPENAI_API_KEYclient = OpenAI(api_key = OPENAI_API_KEY)
userdata.get() 函数安全地访问 Google Colab 中的凭据。gpt-4o。使用这样的环境变量来设置我们的凭据可确保对模型凭据的安全访问,同时保持我们选择模型的灵活性。它也是管理 API 密钥和模型的更好方法,尤其是在不同环境或多个项目中工作时。
我们现在拥有有效构建端到端工作流程的所有资源。现在是时候开始每个工作流组件的技术实现了,从数据处理辅助函数开始。
1、数据处理
我们工作流程的第一步是预处理 PDF 文件并提取其文本内容,这是通过 extract_text_from_pdf 函数实现的。
它将 PDF 文件作为输入,并将其内容作为原始文本数据返回。
def extract_text_from_pdf(pdf_path: str):"""Extract text content from a PDF file using the unstructured library."""elements = partition_pdf(pdf_path, strategy="hi_res")return "\n".join([str(element) for element in elements])
2、Prompt读取
提示存储在单独的 .txt 文件中,并使用以下函数加载。
def read_prompt(prompt_path: str):"""Read the prompt for research paper parsing from a text file."""with open(prompt_path, "r") as f:return f.read()
3、元数据提取
这个函数实际上是我们工作流程的核心。它利用 OpenAI API 来处理给定 PDF 文件的内容。
如果不使用装饰器 @retry,我们可能会遇到 Error Code 429 - Rate limit reached for requests 问题。这主要发生在我们在处理过程中达到速率限制时。我们希望函数继续尝试,直到成功达到目标,而不是失败。
@retry(wait=wait_random_exponential(min=1, max=120), stop=stop_after_attempt(10))def completion_with_backoff(**kwargs):return client.chat.completions.create(**kwargs)
通过在 extract_metadata 函数中使用 completion_with_backoff:
def extract_metadata(content: str, prompt_path: str, model_id: str):"""Use GPT model to extract metadata from the research paper content based on the given prompt."""prompt_data = read_prompt(prompt_path)try:response = completion_with_backoff(model=model_id,messages=[{"role": "system", "content": prompt_data},{"role": "user", "content": content}],temperature=0.2,)response_content = response.choices[0].message.content# Process and return the extracted metadata# ...except Exception as e:print(f"Error calling OpenAI API: {e}")return {}
通过随提示一起发送论文内容,gpt-4o 模型提取提示中指定的结构化信息。
通过将所有逻辑放在一起,我们可以使用 process_research_paper 函数对单个 PDF 文件进行端到端执行,从提取预期的元数据到将最终结果保存为.json 格式。
def process_research_paper(pdf_path: str, prompt: str,output_folder: str, model_id: str):"""Process a single research paper through the entire pipeline."""print(f"Processing research paper: {pdf_path}")try:# Step 1: Extract text content from the PDFcontent = extract_text_from_pdf(pdf_path)# Step 2: Extract metadata using GPT modelmetadata = extract_metadata(content, prompt, model_id)# Step 3: Save the result as a JSON fileoutput_filename = Path(pdf_path).stem + '.json'output_path = os.path.join(output_folder, output_filename)with open(output_path, 'w') as f:json.dump(metadata, f, indent=2)print(f"Saved metadata to {output_path}")except Exception as e:print(f"Error processing {pdf_path}: {e}")
以下是将逻辑应用于单个文档处理的示例:
# Example for a single documentpdf_path = "./data/1706.03762v7.pdf"prompt_path ="./data/prompts/scientific_papers_prompt.txt"output_folder = "./data/extracted_metadata"process_research_paper(pdf_path, prompt_path, output_folder, model_ID)
从上图中,我们可以看到生成的 .json 保存在 ./data/extracted_metadata/ 文件夹中,名称为 1706.0376v7.json,与 PDF 的名称完全相同,但具有不同的扩展名。
下面给出了 json 文件的内容以及突出显示的研究论文,其中突出显示了已提取的目标属性:
从 json 数据中我们注意到所有属性都已成功提取。更棒的是,论文中没有提供 Illia Polosukhin 的机构,人工智能将其保留为空白字段。
{"PaperTitle": "Attention Is All You Need","PublicationYear": "2017","Authors": ["Ashish Vaswani","Noam Shazeer","Niki Parmar","Jakob Uszkoreit","Llion Jones","Aidan N. Gomez","Lukasz Kaiser","Illia Polosukhin"],"AuthorContact": [{"Name": "Ashish Vaswani","Institution": "Google Brain","Email": "avaswani@google.com"},{"Name": "Noam Shazeer","Institution": "Google Brain","Email": "noam@google.com"},{"Name": "Niki Parmar","Institution": "Google Research","Email": "nikip@google.com"},{"Name": "Jakob Uszkoreit","Institution": "Google Research","Email": "usz@google.com"},{"Name": "Llion Jones","Institution": "Google Research","Email": "llion@google.com"},{"Name": "Aidan N. Gomez","Institution": "University of Toronto","Email": "aidan@cs.toronto.edu"},{"Name": "Lukasz Kaiser","Institution": "Google Brain","Email": "lukaszkaiser@google.com"},{"Name": "Illia Polosukhin","Institution": "","Email": "illia.polosukhin@gmail.com"}],"Abstract": "The dominant sequence transduction models are based on complex recurrent or convolutional neural networks that include an encoder and a decoder. The best performing models also connect the encoder and decoder through an attention mechanism. We propose a new simple network architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two machine translation tasks show these models to be superior in quality while being more parallelizable and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task, improving over the existing best results, including ensembles, by over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training costs of the best models from the literature. We show that the Transformer generalizes well to other tasks by applying it successfully to English constituency parsing both with large and limited training data.","SummaryAbstract": "The paper introduces the Transformer, a novel network architecture based solely on attention mechanisms, eliminating the need for recurrence and convolutions. The Transformer achieves superior performance on machine translation tasks, setting new state-of-the-art BLEU scores while being more parallelizable and requiring less training time. Additionally, it generalizes well to other tasks such as English constituency parsing."}此外,附加属性 Summary Abstract 的值如下所示,它完美地总结了最初的摘要,同时保持在提示中提供的两到三个句子约束内。
The paper introduces the Transformer, a novel network architecture based solely on attention mechanisms, eliminating the need for recurrence and convolutions. The Transformer achieves superior performance on machine translation tasks, setting new state-of-the-art BLEU scores while being more parallelizable and requiring less training time. Additionally, it generalizes well to other tasks such as English constituency parsin
现在pipeline适用于单个文档,我们可以实现逻辑来对给定文件夹中的所有文档运行它,这是使用 process_directory 函数实现的。它处理每个文件并将其保存到同一个 extracted_metadata 文件夹中。
# Parse documents from a folderdef process_directory(prompt_path: str, directory_path: str, output_folder: str, model_id: str):"""Process all PDF files in the given directory."""# Iterate through all files in the directoryfor filename in os.listdir(directory_path):if filename.lower().endswith('.pdf'):pdf_path = os.path.join(directory_path, filename)process_research_paper(pdf_path, prompt_path, output_folder, model_id)
以下是如何使用正确的参数调用该函数。
# Define pathsprompt_path = "./data/prompts/scientific_papers_prompt.txt"directory_path = "./data"output_folder = "./data/extracted_metadata"
process_directory(prompt_path, directory_path, output_folder, model_ID)
处理成功显示如下信息,我们可以看到每篇研究论文都已被处理。
本文简要概述了LLM在复杂文档元数据提取中的应用,提取的json数据可以存储在非关系数据库中以供进一步分析。LLM 和正则表达式在内容提取方面各有优缺点,每一种都应根据用例明智地应用。
53AI,企业落地大模型首选服务商
产品:场景落地咨询+大模型应用平台+行业解决方案
承诺:免费POC验证,效果达标后再合作。零风险落地应用大模型,已交付160+中大型企业
2026-07-09
Claude Design 迎来一次重大更新
2026-07-09
GPT-Live:当 AI 学会一边听你说话,一边回应你
2026-07-09
一文读懂Harness Engineering!
2026-07-09
GPT-6要来了!OpenAI彻底抛弃4T旧底座
2026-07-09
AI智能体为何选择MCP而不是API
2026-07-09
OpenAI深夜放出GPT-Live,ChatGPT终于像真人一样说话
2026-07-09
OpenAI 发布新一代语音模型 GPT-Live。山姆·奥特曼:感觉很神奇
2026-07-09
刚刚,OpenAI 官宣 GPT-5.6 本周四全量上线!
2026-04-15
2026-04-24
2026-04-17
2026-04-14
2026-04-24
2026-05-19
2026-04-22
2026-04-24
2026-04-24
2026-04-16
欢迎您使用【53AI 官方网站】(以下简称“本网站”或“我们”)。本《会员服务协议》(以下简称“本协议”)是您(以下简称“会员”或“用户”)与【深圳市博思协创网络科技有限公司】之间关于注册、登录及使用本网站会员服务所订立的法律协议。
在您注册或登录前,请务必审慎阅读、充分理解各条款内容,特别是免除或限制责任的条款、知识产权条款、争议解决条款等。此类条款将以加粗形式提示您注意。 当您通过微信公众号授权、手机验证码验证或其他方式成功登录本网站时,即视为您已完全理解并同意接受本协议的全部内容。
一、 定义
本网站:指由【深圳市博思协创网络科技有限公司】运营的,域名为【53ai.com】的网站及相关移动端页面。
会员服务:指本网站向注册会员提供的知识库文章查阅、内容检索及其他相关增值服务。
知识库内容:指本网站发布的包括但不限于文字、图表、数据、研究报告、行业分析等数字化内容资源。
二、 账号注册与登录
登录方式:本网站支持以下登录方式,您可根据实际情况选择:
微信公众号授权登录:您同意将您的微信OpenID信息授权给本网站,用于创建或关联会员账号。
手机验证码登录:您需提供真实有效的手机号码,并通过短信验证码完成身份验证与登录/注册。
账号安全:您的账号仅限您本人使用,禁止赠与、借用、租用、转让或售卖。因您保管不善导致的账号被盗、密码泄露等损失,由您自行承担。
实名认证:根据相关法律法规要求,我们可能要求您在特定功能下完成实名认证。如您拒绝提供,可能无法使用部分或全部服务。
未成年人保护:若您未满18周岁,请在法定监护人的陪同下阅读本协议,并在征得监护人同意后使用本服务。
三、 服务内容与规范
知识库查阅权限:会员登录后,有权按照其会员等级对应的权限范围,在线浏览、检索本网站知识库中的相关文章及内容。
服务变更:我们有权根据业务发展需要,调整、变更或终止部分服务内容,并将以网站公告、公众号消息等方式提前通知。
禁止行为:您在使用服务时不得实施以下行为:
利用技术手段批量爬取、下载、转存知识库内容;
将知识库内容用于商业目的或未经授权地向第三方传播;
干扰本网站正常运行或侵犯其他用户合法权益;
发布违法违规信息或从事违反公序良俗的活动。
四、 知识产权声明
权利归属:本网站知识库中的排版设计、软件代码等内容的知识产权均归【公司全称】或原权利人所有,受《中华人民共和国著作权法》等法律保护。
有限许可:本网站授予会员一项非独占、不可转让、不可转授权的普通许可,仅限于个人学习、研究之目的在线查阅知识库内容。
侵权追责:未经书面许可,任何单位或个人不得以任何形式复制、转载、摘编、镜像、汇编或以其他方式使用上述内容。一经发现,我们保留追究其法律责任的权利。
五、 个人信息保护
我们重视对您个人信息的保护。关于我们如何收集、使用、存储和保护您的个人信息,请单独阅读 《隐私政策》。
您通过微信公众号授权或手机号验证所提供的信息,我们将严格按照《个人信息保护法》的规定处理,仅用于身份识别、服务提供及安全验证等必要用途。
您可以随时通过网站设置或联系客服行使查阅、更正、删除个人信息及撤回授权同意的权利。
六、 免责声明
内容准确性:知识库内容仅供参考,不构成专业建议。我们不对其完整性、准确性、时效性作任何明示或暗示的保证,您应自行判断并承担使用风险。
不可抗力:因自然灾害、政策法规变化、网络故障、第三方平台接口异常(如微信接口维护、运营商短信通道故障)等不可抗力导致的服务中断或延迟,我们不承担违约责任。
第三方链接:本网站可能包含指向第三方网站的链接,该等网站的内容和服务不受我们控制,请您自行甄别风险。
七、 违约责任
如您违反本协议约定,我们有权视情节采取警告、限制功能、暂停服务、注销账号等措施,并保留要求赔偿损失的权利。
如因您的违约行为导致我们遭受行政处罚、第三方索赔或商誉损失,您应承担全部赔偿责任(包括但不限于罚款、赔偿金、律师费、公证费等)。
八、 法律适用与争议解决
本协议的订立、执行和解释均适用中华人民共和国大陆地区法律。
因本协议产生的或与本协议有关的任何争议,双方应友好协商解决;协商不成的,任何一方均可向【公司所在地】有管辖权的人民法院提起诉讼。
九、 其他
本协议构成双方就本服务达成的完整协议,取代此前任何口头或书面约定。
本协议任一条款被认定为无效或不可执行的,不影响其他条款的效力。
我们对本协议享有最终解释权,并在法律允许的范围内保留随时修改的权利。修改后的协议一经公布即生效,继续使用服务即视为同意修订内容。