【问题标题】:Python PyMuPDF searchFor method not workingPython PyMuPDF searchFor 方法不起作用
【发布时间】:2018-12-21 09:18:47
【问题描述】:

我在 python 中使用 PyMuPDF 库来搜索 PDF 文档中的特定文本,然后突出显示它。

pdf_document = fitz.open(pdf_path) for i in range(len(page_num)):
page=pdf_document[page_num[i]]
for item in search_terms: search_instances = page.searchFor(item) for inst in search_instances: page.addHighlightAnnot(inst)

PDF文档图片如下:

我可以突出显示 PDF 文档中的所有术语,但搜索词“毛利润”除外。 searchFor() 返回一个空列表而不是坐标。这与质量差的 PDF 有什么关系吗?如果是这样,它也不应该适用于其他搜索字词。它适用于“营业额”和“销售成本”等字词

有什么想法吗?

【问题讨论】:

    标签: python string pdf search text


    【解决方案1】:

    好像是非文本PDF。

    您必须使用 pytesseract 之类的 OCR 将其转换为文本 pdf,然后使用 fitz 突出显示它。

    类似的东西应该可以工作:

    from pdf2image import convert_from_path, convert_from_bytes 
    from fpdf import FPDF
    
    pytesseract.pytesseract.tesseract_cmd = /pathto/Tesseract-OCR/tesseract.exe'
    
    def string_stream(s, separators="\n"):
        start = 0
        for end in range(len(s)):
            if s[end] in separators:
                yield s[start:end]
                start = end + 1
        if start < end:
            yield s[start:end+1]
    
    
    def multipage_simple(whole_text):
        pdf = FPDF(format='letter') #pdf format
        pdf.add_page() #create new page
        pdf.set_font("Arial", size=12) # font and textsize
        cnt = 1
        stream = string_stream(normalize(whole_text))
        for s in stream:
            pdf.cell(200, 10, txt=s, ln=cnt, align="L")
            cnt += 1
        pdf.output("multipage_simple.pdf", "F")
    
    def get_text_from_pdf_with_ocr(file_name_to_image_pdf):
        res = []
        seq_of_images = convert_from_path(file_name)
        for img in seq_of_images:
            text = re.sub(REMOVAL_SPECIAL_CHARACTER_PATTERN, " ", string=pytesseract.image_to_string(img))
            res += [text]
        return res
    

    然后做:

    doc = fitz.open("multipage_simple.pdf")
    

    您可以通过以下方式获取整个文本:

    text_ = get_text_from_pdf_with_ocr(pdf_id)
    whole_text = reduce(lambda x, y: x + y, text_)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多