• 结巴(jieba)分词 java 实现


    前言

    最近因为需要学习新闻推荐相关的知识,所以学习分词相关的知识

    1引入 pom 依赖

    <dependency>
       	<groupId>com.huaban</groupId>
        <artifactId>jieba-analysis</artifactId>
         <version>1.0.2</version>
     </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    普通分词实现代码

    import com.huaban.analysis.jieba.JiebaSegmenter;
    import data.recomend.util.TextDealutil;
    import org.apache.commons.io.FileUtils;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class SplitWord {
    
        private static String basePath = "C:\\project\\idea4\\dataRecommend\\src\\main\\resources\\data\\";
        public static void main(String[] args) throws IOException {
            String content = "《开端》《镜双城》《淘金》三部热播剧均有她,你发现了吗?";
            content = TextDealutil.specialCharacters(content);
            List<String> stop_words = FileUtils.readLines(new File(basePath + "files\\stop_words.txt"));
            JiebaSegmenter segmenter = new JiebaSegmenter();
            List<String> result = segmenter.sentenceProcess(content);
            System.out.println("没有过滤停用词======" + result);
            result = result.stream().map(o -> o.trim()).filter(o -> !stop_words.contains(o)).collect(Collectors.toList());
            System.out.println("过滤停用词=========" + result);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    结果展示:
    在这里插入图片描述
    stop_words.txt 停用词类似于一些符号,或者语气词之类的,通过以上的测试结果可以看出来

    !
    "
    #
    $
    %
    &
    '
    (
    )
    *
    +
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    TextDealutil,自定义的去除文本的特殊字符,可以不需要这个类,或者自己重写对特殊字符进行替换也行

    2 加载自定义词典

    2.1 情况

    对于某些分词,应该是分成一个词,但是分出来确实多个词的情况,比如说
    在这里插入图片描述
    比如一些专业名词,还有一些人名之类的,“周冬雨”,我们希望分词之后的是“周冬雨”,而不是“周”、“冬雨”这样的。

    其实结巴分词默认的是时候,会加载包下的一个默认dict.txt
    在这里插入图片描述

    每一个关键词一行,每一列分别表示:关键字,词频,词性,用空格分隔开的

    所以我们在自定义词典的时候,也需要按照这个格式,然后加载到环境中

    2.2自定义 词典 dict.txt

    周冬雨 3 n
    郭艾伦 3 n
    张雨霏 3 nr
    林郑月 3 nr

    2.3 加载自定义词典

    也就是通过 WordDictionary加载自定义的词典

    		// 加载自定义的词典
            Path path = FileSystems.getDefault().getPath(basePath+"/files", "dict.txt");
            WordDictionary.getInstance().loadUserDict(path);
            JiebaSegmenter jiebaSegmenter = new JiebaSegmenter();
            List<String> strings = jiebaSegmenter.sentenceProcess("周杰伦周冬雨");
            strings.stream().forEach(System.out::println);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    结果

    main dict load finished, time elapsed 578 ms
    user dict C:\project\idea4\dataRecommend\src\main\resources\data\files\dict.txt load finished, tot words:4, time elapsed:0ms
    model load finished, time elapsed 43 ms.
    周杰伦
    周冬雨

    打印的结果包含加载项目路劲下自定义的词典和解析结果

    3关于词性的问题

    3.1 python 中关于词性的使用方式

    jieba.analyse.extract_tags(
                        self.content,
                        topK=10,
                        withWeight=False,
                        allowPOS=('ns', 'n', 'vn', 'v')
                    )
         ##   以下为注释
        Extract keywords from sentence using TF-IDF algorithm.
        Parameter:
            - topK: return how many top keywords. `None` for all possible words.
            - withWeight: if True, return a list of (word, weight);
                          if False, return a list of words.
            - allowPOS: the allowed POS list eg. ['ns', 'n', 'vn', 'v','nr'].
                        if the POS of w is not in this list,it will be filtered.
            - withFlag: only work with allowPOS is not empty.
                        if True, return a list of pair(word, weight) like posseg.cut
                        if False, return a list of words
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    其中 allowPOS,表示分词结果之后,保留什么词性的分词,
    topK表示根据排序之后的结果,取前 TopK个结果

            if allowPOS:
                allowPOS = frozenset(allowPOS)
                words = self.postokenizer.cut(sentence)
            else:
                words = self.tokenizer.cut(sentence)
            freq = {}
            for w in words:
            	## 获取指定词性的分词结果
                if allowPOS:
                    if w.flag not in allowPOS:
                        continue
                    elif not withFlag:
                        w = w.word
                wc = w.word if allowPOS and withFlag else w
                ## 停用词过滤的地方
                if len(wc.strip()) < 2 or wc.lower() in self.stop_words:
                    continue
                freq[w] = freq.get(w, 0.0) + 1.0
            total = sum(freq.values())
            for k in freq:
                kw = k.word if allowPOS and withFlag else k
                freq[k] *= self.idf_freq.get(kw, self.median_idf) / total
    		# 排序
            if withWeight:
                tags = sorted(freq.items(), key=itemgetter(1), reverse=True)
            else:
                tags = sorted(freq, key=freq.__getitem__, reverse=True)
             # 取排序好的TopK个结果
            if topK:
                return tags[:topK]
            else:
                return tags
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    3.2 java 中当前版本不支持词性

    huaban 的 github 地址中

    https://github.com/huaban/jieba-analysis

    有关于介绍,也就是说当前这个版本没有不支持词性分词
    在这里插入图片描述

  • 相关阅读:
    HTML 揭秘:HTML 编码快速入门
    app逆向(9)|APP关于抓包的常见问题
    MongoDB 数据库性能优化技巧
    @SentinelResource注解的使用
    IBM Spectrum Symphony 获享高度可扩展、高吞吐量、低延迟的工作负载管理
    计算机程序设计艺术习题解答(Excercise 1.2.2-28~30题)
    PlayWright(十二)- PO模式
    ​[openCV Calibration] 相机矫正
    【智能家居-大模型】构建未来,聆思大模型智能家居交互解决方案正式发布
    皮球 - 博客园主题
  • 原文地址:https://blog.csdn.net/qq_20667511/article/details/125405663