如何用Python从两列pdf中提取文本?

2024-04-23 19:56:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有: enter image description here

我有一份两栏的PDF文件格式。是有没有一种方法可以根据两列格式来阅读每一份PDF而不需要单独裁剪每个PDF?在


Tags: 方法pdf格式
1条回答
网友
1楼 · 发布于 2024-04-23 19:56:13

这是我用于常规pdf解析的代码,在该图像上似乎可以正常工作(我下载了一个图像,因此它使用了光学字符识别,因此它与普通OCR一样精确)。注意,这会标记文本。还要注意,您需要安装tesseract才能使其正常工作(pytesseract只是让tesseract从python中工作)。Tesseract是免费和开源的。在

from PIL import Image
import pytesseract
import cv2
import os

def parse(image_path, threshold=False, blur=False):
    image = cv2.imread(image_path)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    if threshold:
        gray = cv2.threshold(gray, 0, 255, \
            cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
    if blur: #useful if salt-and-pepper background.
        gray = cv2.medianBlur(gray, 3)
    filename = "{}.png".format(os.getpid())
    cv2.imwrite(filename, gray) #Create a temp file
    text = pytesseract.image_to_string(Image.open(filename))
    os.remove(filename) #Remove the temp file
    text = text.split() #PROCESS HERE.
    print(text)
a = parse(image_path, True, False)

相关问题 更多 >