一次从本地存储读取多个pdf文件

Reading multiple pdf files from local storage at once

目前使用 google 愿景 API 我只能从本地存储中读取一个 pdf 文件。我想弄清楚如何一次从本地存储中读取多个 pdf 文件,而不必手动更改我想在代码中读取的文件。有办法吗?

根据您的要求,我参考了这个documentation

我使用 Python 客户端库来编写代码。

我的本地机器目录结构:

home->
    myfolder->
        myfolder1->
                input1.pdf
                input2.pdf

我在我的目录中存储了两个 pdf 文件,文本是一次一个地从 pdf 文件中提取的。

您可以参考下面提到的代码:

demo.py:

import io
import os

from google.cloud import vision_v1

directory="/home/myfolder/myfolder1/"
for file in os.listdir(directory):
    if  file.endswith(".pdf"):

        client = vision_v1.ImageAnnotatorClient()

# Supported mime_type: application/pdf, image/tiff, image/gif
        mime_type = "application/pdf"
        with open(os.path.join(directory,file), 'rb') as f:
            content = f.read()
        input_config = {"mime_type": mime_type, "content": content}
        features = [{"type_": vision_v1.Feature.Type.DOCUMENT_TEXT_DETECTION}]

# The service can process up to 5 pages per document file. Here we specify
# the first, second, and last page of the document to be processed.
        pages = [1, 2, -1]
        requests = [{"input_config": input_config, "features": features, "pages": pages}]

        response = client.batch_annotate_files(requests=requests)
        for image_response in response.responses[0].responses:
            print(u"Full text: {}".format(image_response.full_text_annotation.text))
            for page in image_response.full_text_annotation.pages:
                for block in page.blocks:
                    print(u"\nBlock confidence: {}".format(block.confidence))
                    for par in block.paragraphs:
                        print(u"\tParagraph confidence: {}".format(par.confidence))
                        for word in par.words:
                            print(u"\t\tWord confidence: {}".format(word.confidence))
                            for symbol in word.symbols:

                                print(
                                u"\t\t\tSymbol: {}, (confidence: {})".format(
                                symbol.text, symbol.confidence
                            )
                        )


输出:

对于 input1.pdf:

对于 input2.pdf: