tika解析文本

1.业务需求

        需要对文章进行内容提取或者分段展示,以及下游的LLM处理。这里就涉及到将上传的文档进行文本内容提取。

2.需求设计

        在现有的开源工具中,我们选中了tika,主要优势是版本的更新,解析的全面性,使用的便捷性。

3.代码实现

        maven依赖

        <dependency>
            <groupId>org.apache.tika</groupId>
            <artifactId>tika-core</artifactId>
            <version>2.9.0</version>
        </dependency>

简单的例子

//        Tika t = new Tika();
//        String s = t.parseToString(new File("D:\\ex-wangwei020\\接口报告.docx"));
//        System.out.println(s);

a) 将文档内容提取为html,以供前端直接展示

    public String parseToHTML(File file) throws IOException, SAXException, TikaException {
        ContentHandler handler = new ToXMLContentHandler();

        AutoDetectParser parser = new AutoDetectParser();
        Metadata metadata = new Metadata();
        try (InputStream stream = Files.newInputStream(file.toPath())){
            parser.parse(stream, handler, metadata);
            return handler.toString();
        }
    }

b) 根据固定标签获取对应的内容

一种方法可以根据上面转换好的html,利用jSoup提取

第二种方法可以使用xhtml去提取,代码如下

public void getTagVal(){
        XPathParser xhtmlParser = new XPathParser("xhtml", XHTMLContentHandler.XHTML);
        org.apache.tika.sax.xpath.Matcher divContentMatcher = xhtmlParser.parse("/xhtml:html/xhtml:body/xhtml:p/descendant::node()");//这里提取了-html-body-p 标签下的内容。可以提取的标签有h1-h6 table,具体参考XHTMLContentHandler

        ContentHandler handler = new MatchingContentHandler(
                new ToXMLContentHandler(), divContentMatcher);

        AutoDetectParser parser = new AutoDetectParser();
        Metadata metadata = new Metadata();
        ParseContext context = new ParseContext();
        context.set(Parser.class, parser);
        try (InputStream stream = Files.newInputStream(new File("C:\\Users\\Administrator\\Downloads\\test2.docx").toPath())) {
            parser.parse(stream, handler, metadata);                        
            System.out.println("============================");
            System.out.println(handler.toString());
        }
}

c) 获取文档中内嵌文档的内容-官方样例

    public String parseNoEmbeddedExample() throws IOException, SAXException, TikaException {
        AutoDetectParser parser = new AutoDetectParser();
        BodyContentHandler handler = new BodyContentHandler();
        Metadata metadata = new Metadata();
        try (InputStream stream = ParsingExample.class.getResourceAsStream("test_recursive_embedded.docx")) {
            parser.parse(stream, handler, metadata, new ParseContext());
            return handler.toString();
        }
    }

参考文档

asf - Revision 1918030: /tika/trunk/tika-example

  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值