Java从Python调用,无需加载类路径。

2024-04-27 03:24:27 发布

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

我正在用Python调用javajar文件

def extract_words(file_path):
    """
    Extract words and bounding boxes

    Arguments:
        file_path {[str]} -- [Input file path]

    Returns:
        [Document]
    """

    extractor = PDFBoxExtractor(file_path=file_path,jar_path="external/pdfbox-app-2.0.15.jar",class_path="external")

    document = extractor.run()
    return document

在某个地方:

pipe = subprocess.Popen(['java',
                             '-cp',
                             '.:%s:%s' %
                             (self._jar_path,
                             self._class_path) ,
                             'PrintTextLocations',
                             self._file_path],
                            stdout=subprocess.PIPE)
    output = pipe.communicate()[0].decode()

这很有效。但问题是jar很重,当我必须在循环中多次调用它时,每次加载jar文件需要3-4秒。如果我在一个循环中运行100次,它会给进程增加300-400秒

有没有办法让java的类路径保持活动状态,而不是每次都加载jar文件?以时间优化的方式做这件事最好的方法是什么


Tags: 文件pathselfdefjavadocumentexternalclass
1条回答
网友
1楼 · 发布于 2024-04-27 03:24:27

可以将PDFBoxExtractor封装在类中,使其成为类成员。在类的构造函数中初始化PDFBoxExtractor。如下所示:

class WordExtractor:

    def __init__(self):
        self.extractor = PDFBoxExtractor(file_path=file_path,jar_path="external/pdfbox-app-2.0.15.jar",class_path="external")

    def extract_words(self,file_path):
        """
        Extract words and bounding boxes

        Arguments:
            file_path {[str]}   [Input file path]

        Returns:
            [Document]
        """

        document = self.extractor.run()
        return document

下一步是在循环外创建WordExtractor类的实例

word_extractor = WordExtractor()

#your loop would go here
while True:
    document = word_extractor.extract_words(file_path);

这只是解释概念的示例代码。你可以根据你的要求调整它

希望这有帮助

相关问题 更多 >