7

我可以使用哪些 python 包来找出特定“搜索字符串”位于哪个页面上?

我查看了几个 python pdf 包,但不知道应该使用哪一个。 PyPDF似乎没有这个功能,而PDFMiner似乎对于这样简单的任务来说是一种过度杀伤力。有什么建议吗?

更准确地说:我有几个 PDF 文档,我想提取字符串 “Begin” 和字符串 “End” 之间的页面。

4

5 回答 5

18

我终于发现 pyPDF 可以提供帮助。我发布它以防它可以帮助其他人。

(1) 定位字符串的函数

def fnPDF_FindText(xFile, xString):
    # xfile : the PDF file in which to look
    # xString : the string to look for
    import pyPdf, re
    PageFound = -1
    pdfDoc = pyPdf.PdfFileReader(file(xFile, "rb"))
    for i in range(0, pdfDoc.getNumPages()):
        content = ""
        content += pdfDoc.getPage(i).extractText() + "\n"
        content1 = content.encode('ascii', 'ignore').lower()
        ResSearch = re.search(xString, content1)
        if ResSearch is not None:
           PageFound = i
           break
     return PageFound

(2) 提取感兴趣页面的功能

  def fnPDF_ExtractPages(xFileNameOriginal, xFileNameOutput, xPageStart, xPageEnd):
      from pyPdf import PdfFileReader, PdfFileWriter
      output = PdfFileWriter()
      pdfOne = PdfFileReader(file(xFileNameOriginal, "rb"))
      for i in range(xPageStart, xPageEnd):
          output.addPage(pdfOne.getPage(i))
          outputStream = file(xFileNameOutput, "wb")
          output.write(outputStream)
          outputStream.close()

我希望这对其他人有帮助

于 2013-01-17T21:35:40.010 回答
2

除了@user1043144 提到的,

与 python 3.x 一起使用

使用 PyPDF2

import PyPDF2

使用open代替file

PdfFileReader(open(xFile, 'rb'))
于 2018-12-03T04:10:29.760 回答
2

我能够使用下面的代码成功获得输出。

代码:

import PyPDF2
import re

# Open the pdf file
object = PyPDF2.PdfFileReader(r"C:\TEST.pdf")

# Get number of pages
NumPages = object.getNumPages()

# Enter code here
String = "Enter_the_text_to_Search_here"

# Extract text and do the search
for i in range(0, NumPages):
    PageObj = object.getPage(i)
    Text = PageObj.extractText()
    if re.search(String,Text):
         print("Pattern Found on Page: " + str(i))

样本输出:

Pattern Found on Page: 7
于 2019-06-28T11:17:59.703 回答
1

使用python查找搜索字符串位于pdf文档中的哪个页面

PyPDF2

 # import packages
    import PyPDF2
    import re
    
    # open the pdf file
    object = PyPDF2.PdfFileReader(r"source_file_path")
    
    # get number of pages
    NumPages = object.getNumPages()
    
    # define keyterms
    String = "P4F-21B"
    
    # extract text and do the search
    for i in range(0, NumPages):
        PageObj = object.getPage(i)
        Text = PageObj.extractText()
        ResSearch = re.search(String, Text)
        if ResSearch != None:
            print(ResSearch)
            print("Page Number" + str(i+1))

输出:

<re.Match object; span=(57, 64), match='P4F-21B'>
Page Number1

PyMuPDF

import fitz
import re

# load document
doc = fitz.open(r"C:\Users\shraddha.shetty\Desktop\OCR-pages-deleted.pdf")

# define keyterms
String = "P4F-21B"

# get text, search for string and print count on page.
for page in doc:
    text = ''
    text += page.get_text()
    if len(re.findall(String, text)) > 0:
        print(f'count on page {page.number + 1} is: {len(re.findall(String, text))}')
于 2021-11-24T09:08:30.007 回答
0

用 PYDF2 更新答案

import re 
import PyPDF2


def pdf_find_text(xfile_pdf, xsearch_string, ignore_case = False):
    '''
    find page(s) on which a given text is located in a pdf
    input: pdf file and the string to search 
    (string to search can be in a regex like 'references\n')
    
    N.B: 
    results need to be checked 
    in case of pdf whose page numbers are not zero indexed , 
    the results seems off (by one page) 
    '''
    
    xlst_res = []
    
    xreader = PyPDF2.PdfFileReader(xfile_pdf)

    for xpage_nr, xpage in enumerate(xreader.pages):
        xpage_text = xpage.extractText()
        xhits = None
        if ignore_case == False:
            xhits = re.search(xsearch_string, xpage_text.lower())
        else:
            xhits = re.search(xsearch_string, xpage_text.lower(), re.IGNORECASE)

        if xhits:
            xlst_res.append(xpage_nr)
    return {'num_pages': xreader.numPages, 'page_hits': xlst_res}

def pdf_extract_pages(xpdf_original, xpdf_new , xpage_start, xpage_end):
    '''
    given a pdf extract a page range and save it in a new pdf file 
    
    '''
    with open(xpdf_original, 'rb') as xfile_1, open(xpdf_new , 'wb') as xfile_2:
        xreader = PyPDF2.PdfFileReader(xfile_1)
        xwriter  = PyPDF2.PdfFileWriter()
        for xpage_nr in range(xpage_start, xpage_end ):
            xwriter.addPage(xreader.getPage(xpage_nr))
        xwriter.write(xfile_2)

于 2021-10-13T15:59:13.807 回答