背景
近期再次遇到了关于知识库的需求,对照[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领域,存在对大量的文本文件进行内容提取的场景,此组件能满足绝大部分场景。
同样可以进行元数据的读取,本文不对此进行特别介绍,可自行查找资料。