如何阻止 pdfplumber 读取每个页面的标题?

2024-03-31

我希望 pdfplumber 从用户给出的随机 pdf 中提取文本。问题是 pdfplumber 还从每个页面中提取标题文本或标题。如何对 pdfplumber 进行编程,使其不读取页眉(标题)和页码(或页脚,如果可能)?

这是代码:

import pdfplumber

all_text = ""

pdf = pdfplumber.open(file)
for pdf_page in pdf.pages:
    one = pdf_page.extract_text()
    all_text = all_text + '\n' + str(one)
    print(all_text)

where file是 PDF 文档...


我认为你不能。

但是,您可以使用以下命令裁剪文档crop方法。这样,您可以仅提取页面裁剪部分的文本,而忽略页眉和页脚。 当然,这种方法需要您提前知道页眉和页脚的高度。

下面是坐标的解释:

x0 = % Distance of left side of character from left side of page.
top = % Distance of top of character from top of page.
x1 = % Distance of right side of character from left side of page.
bottom = % Distance of bottom of the character from top of page.

这是代码:

# Get text of whole document as string
crop_coords = [x0, top, x1, bottom]
text = ''
pages = []
with pdfplumber.open(filename) as pdf:
    for i, page in enumerate(pdf.pages):
        my_width = page.width
        my_height = page.height
        # Crop pages
        my_bbox = (crop_coords[0]*float(my_width), crop_coords[1]*float(my_height), crop_coords[2]*float(my_width), crop_coords[3]*float(my_height))
        page_crop = page.crop(bbox=my_bbox)
        text = text+str(page_crop.extract_text()).lower()
        pages.append(page_crop)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何阻止 pdfplumber 读取每个页面的标题? 的相关文章

随机推荐