第一步是安装工具库1、tika——用于文档类型检测和从各种文件格式中提取内容2、wand——一个简单的基于ctypes的ImageMagick绑定3、pytesseract——OCR识别工具创建一个虚拟环境,安装这些工具python-mvenvvenvsourcevenv/bin/activatepipinstalltikawandpytesseract第二步是写代码。如果pdf文件既有文字又有图片,下面的代码可以直接识别文字:['content'].strip())这还不够,我们还需要对图片部分进行fail:defextract_text_image(from_file,lang='deu',image_type='jpeg',resolution=300):print("--解析图片",from_file,"--")print("------------------------------")pdf_file=wi(filename=from_file,resolution=resolution)image=pdf_file.convert(image_type)image_blobs=[]用于图像中的img。序列:img_page=wi(image=img)image_blobs.append(img_page.make_blob(image_type))extract=[]forimg_blobinimage_blobs:image=Image.open(io.BytesIO(img_blob))text=pytesseract.image_to_string(image,lang=lang)extract.append(text)foriteminextract:forlineinitem.split("\n"):打印(line)合并一下,完整代码如下:importioimportsysfromPILimportImageimportpytesseractfromwand.imageimportImageaswifromtikaimportparserdefextract_text_image(from_file,lang='deu',image_type='jpeg',resolution=300):print("--解析图片",from_file,"--")print("--------------------------------")pdf_file=wi(文件名=from_file,resolution=resolution)image=pdf_file.convert(image_type)forimginimage.sequence:img_page=wi(image=img)image=Image.open(io.BytesIO(img_page.make_blob(image_type)))text=pytesseract.image_to_string(image,lang=lang)forpartintext.split("\n"):print("{}".format(part))defparse_text(from_file):print("--解析文本",from_file,"--")text_raw=parser.from_file(from_file)print("------------------------------")print(text_raw['content'].strip())打印("------------------------------")if__name__=='__main__':parse_text(sys.argv[1])extract_text_image(sys.argv[1],sys.argv[2])第三步,Executeifexample.pdf是这样的:在命令行中执行:pythonrun.pyexample.pdfdeu|xargs-0echo>extract.txtextract.txt最终结果如下:--解析文本example.pdf---------------------------------标题纯文本内容纯文本幻灯片1幻灯片2---------------------------------解析图片example.pdf------------------------------------TitlepuretextContentpuretextTitleinimageTextinimage大家可能会问,如果是简体中文,lang参数传什么,传'chi_sim',其实官方是有解释的,链接如下:https://github.com/tesseract-……以上就是本次分享的全部内容。现在欢迎想要学习编程的朋友们关注Python技术大本营获取更多技能和教程。
