加载 pdf 是复杂并且有多种不同方式的1. PyPDFLoaderfromlangchain_community.document_loadersimportPyPDFLoader loaderPyPDFLoader(90-文档-Data/黑悟空/黑神话悟空.pdf)pagesloader.load()2. pymupdfimportpymupdf# 打开PDF文件docpymupdf.open(90-文档-Data/黑悟空/黑神话悟空.pdf)text[page.get_text()forpageindoc]3. pdf2image pytesseract# 扫描图片型 PDF建议用 pytesseract pdf2image# sudo apt-get install tesseract-ocr# sudo apt-get install tesseract-ocr-chi-simimportpdf2imageimportpytesseractimportos# 创建 output 目录output_diroutputos.makedirs(output_dir,exist_okTrue)# 将 PDF 转换为图片并保存imagespdf2image.convert_from_path(90-文档-Data/黑悟空/黑神话悟空.pdf)fori,imageinenumerate(images):image.save(f{output_dir}/page_{i1}.png)# 使用 pytesseract 提取文本fori,imageinenumerate(images):textpytesseract.image_to_string(image,langchi_sim)4. LlamaParse 和 MarkdownElementNodeParser# 需要LLAMA_CLOUD_API_KEYfromdotenvimportload_dotenv load_dotenv()# LlamaParse PDF reader for PDF Parsingfromllama_parseimportLlamaParse documentsLlamaParse(result_typemarkdown).load_data(90-文档-Data/黑悟空/黑神话悟空.pdf)print(documents)fromllama_index.core.node_parserimportMarkdownElementNodeParser node_parserMarkdownElementNodeParser()nodesnode_parser.get_nodes_from_documents(documents)print(nodes)5. UnstructuredLoaderfromlangchain_unstructuredimportUnstructuredLoader loaderUnstructuredLoader(file_path90-文档-Data/山西文旅/云冈石窟-en.pdf,# PDF文件路径strategyhi_res,# 使用高分辨率策略进行文档处理# partition_via_apiTrue, # 通过API进行文档分块# coordinatesTrue, # 提取文本坐标信息)docs[]# lazy_load() 是一种延迟加载方法# 它不会一次性将所有文档加载到内存中而是在需要时才逐个加载文档# 这对于处理大型PDF文件时可以节省内存使用fordocinloader.lazy_load():docs.append(doc)print(docs)6. 导入unstructured的partition函数用于PDF解析# 导入unstructured的partition函数用于PDF解析fromunstructured.partition.autoimportpartition# 设置PDF文件路径filename90-文档-Data/黑悟空/黑神话悟空.pdf# 使用partition函数解析PDF文件# content_type指定文件类型为PDFelementspartition(filenamefilename,content_typeapplication/pdf)# 展示解析出的elements的类型和内容print(PDF解析后的Elements类型:)fori,elementinenumerate(elements[:5]):print(f\nElement{i1}:)print(f类型:{type(element).__name__})print(f内容:{str(element)})print(-*50)# 统计不同类型elements的数量element_types{}forelementinelements:element_typetype(element).__name__ element_types[element_type]element_types.get(element_type,0)1print(\nElements类型统计:)forelement_type,countinelement_types.items():print(f{element_type}:{count}个)