且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

【从入门到放弃-Java】工具-词频分析

更新时间:2022-04-02 01:00:15

前言

最近有根据文件内容进行词频分析的需求,如果是纯英文的,写个程序处理比较容易,但涉及到中文词频分析,最关键的一步就是中文分词。

搜了不少文章,最后找到一篇比较好用的 Java实现中文词频统计。主要利用了ansj_seg进行中文分词,分词后再进行词频统计。

针对文章中提供的代码示例,做了稍许改动,贴在下面 做个记录。

依赖

添加最新版ansj_seg依赖

<dependency>
    <groupId>org.ansj</groupId>
    <artifactId>ansj_seg</artifactId>
    <version>5.1.6</version>
</dependency>

代码实现

代码可见 AloofJr

package com.my.tools.ansj;

import com.alibaba.common.lang.StringUtil;
import org.ansj.splitWord.analysis.ToAnalysis;

import java.io.*;
import java.util.*;
/**
 * 对文件中文分词后,根据词频排序输出
 * @author wq
 * @date 2020/4/8
 */
public class Analysis {
    public static void main(String[] args) throws IOException {
        wordFrequency("");
    }

    public static void wordFrequency(String path) throws IOException {
        List<Map.Entry<String, Integer>> wordList = getWordList(path);
        wordList.forEach(entry -> {
            System.out.println(entry.getKey() + "\t" + entry.getValue());
        });
    }

    /**
     * 获取 分词-词频 列表
     * */
    private static List<Map.Entry<String, Integer>> getWordList(String path) throws IOException {
        Map<String, Integer> map = new HashMap<>(16);

        String result = ToAnalysis.parse(getString(path)).toStringWithOutNature();

        //分词后的内容,分词间使用英文逗号分隔。
        String[] words = result.split(",");

        for (String word : words) {

            String str = word.trim();

            // 过滤空白字符

            if (StringUtil.isBlank(str)) {
                continue;
            }

            // 过滤一些高频率的符号

            else if (str.matches("[)|(|.|,|。|+|-|“|”|:|?|\\s]")) {
                continue;
            }

            // 此处过滤长度为1的str
            else if (str.length() < 2) {
                continue;
            }

            if (!map.containsKey(word)) {

                map.put(word, 1);

            } else {

                int n = map.get(word);

                map.put(word, ++n);

            }

        }

        return sortByValue(map);
    }

    /**
     * 根据词频从高到低排序
     * */
    private static List<Map.Entry<String, Integer>> sortByValue(Map<String, Integer> map) {
        if (map == null) {
            return null;
        }
        List<Map.Entry<String, Integer>> list = new ArrayList<>();
        list.addAll(map.entrySet());

        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });

        return list;
    }

    /**
     * 获取文件内容
     * */
    private static String getString(String path) throws IOException {

        FileInputStream inputStream = new FileInputStream(new File(path));

        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

        StringBuilder strBuilder = new StringBuilder();


        String line;

        while ((line = reader.readLine()) != null) {

            strBuilder.append(line);

        }

        reader.close();

        inputStream.close();

        return strBuilder.toString();

    }
}

参考

作者:Asche   

出处:https://www.cnblogs.com/asche/p/9673611.html

更多文章

见我的博客:https://nc2era.com

written by AloofJr,转载请注明出处