[文本提取]基于Apache Tika的文本内容提取

原创
2023/09/21 19:10
阅读数 23

背景

  近期再次遇到了关于知识库的需求,对照[langchain-ChatGLM 本地知识库],发现提取文本内容的功能在这个领域中必不可少,故对其进行了研究。

编码

  使用Spring Maven 与 Apache Tika进行整合,完成对文本内容提取的功能。

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.apache.tika</groupId>
                <artifactId>tika-bom</artifactId>
                <version>2.9.0</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependency>
        <groupId>org.apache.tika</groupId>
        <artifactId>tika-core</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.tika</groupId>
        <artifactId>tika-parsers-standard-package</artifactId>
    </dependency>
@Configuration
public class PapTikaConfig {
    @Autowired
    private ResourceLoader resourceLoader;

    @Bean
    public Tika tika() throws TikaException, IOException, SAXException {

        Resource resource = resourceLoader.getResource("classpath:tika-config.xml");
        InputStream inputStream = resource.getInputStream();

        TikaConfig config = new TikaConfig(inputStream);
        Detector detector = config.getDetector();
        Parser autoDetectParser = new AutoDetectParser(config);

        return new Tika(detector, autoDetectParser);
    }
}
    @Autowired
    private Tika tika;

    @Test
    void tika() throws Exception {
        String[] filePathArray = new String[]{"pap.pptx", "pap.txt", "pap.xlsx", "pap.docx", "pap.pdf"};
        for(String filPath : filePathArray) {
            String s = tika.parseToString(new File(filPath));
        }
    }

总结

  在NLP领域,存在对大量的文本文件进行内容提取的场景,此组件能满足绝大部分场景。

  同样可以进行元数据的读取,本文不对此进行特别介绍,可自行查找资料。

参考

  1. https://gitee.com/alexgaoyh/pap4j-tika
  2. https://tika.apache.org/
  3. https://xie.infoq.cn/article/fcae0319d93d8acb7e3cfa63a
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
0
分享
返回顶部
顶部