溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么用Java讀取文件統(tǒng)計(jì)返回文件中包含的出現(xiàn)頻率最高的3個(gè)Java關(guān)鍵字

發(fā)布時(shí)間:2021-07-09 09:15:07 來源:億速云 閱讀:194 作者:chen 欄目:編程語言

這篇文章主要介紹“怎么用Java讀取文件統(tǒng)計(jì)返回文件中包含的出現(xiàn)頻率最高的3個(gè)Java關(guān)鍵字”,在日常操作中,相信很多人在怎么用Java讀取文件統(tǒng)計(jì)返回文件中包含的出現(xiàn)頻率最高的3個(gè)Java關(guān)鍵字問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”怎么用Java讀取文件統(tǒng)計(jì)返回文件中包含的出現(xiàn)頻率最高的3個(gè)Java關(guān)鍵字”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!

  • 前言

昨天幫助還在讀大學(xué)的朋友做一道Java題,記錄下來。題目大致的意思是 統(tǒng)計(jì)返回文件中包含的出現(xiàn)頻率最高的3個(gè)Java關(guān)鍵字

  •  程序設(shè)計(jì)思路

讀取文件肯定要用到 io 獲取到文本的內(nèi)容。

使用正則表達(dá)式讀取到的文本是否是一個(gè)單詞

判斷得到的這個(gè)單詞是否是java關(guān)鍵字

使用 TreeMap 暫存統(tǒng)計(jì)結(jié)果。key 是關(guān)鍵字 value 是出現(xiàn)的次數(shù)

對TreeMap的value進(jìn)行降序排序,從而取出出現(xiàn)頻率最高的java關(guān)鍵字。

  •  代碼

主要講解都在注釋中

package com.ioword;

import com.alibaba.fastjson.JSON;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 統(tǒng)計(jì)返回文件中包含的出現(xiàn)頻率最高的3個(gè)Java關(guān)鍵字
 *
 * @author lishuzhen
 * @date 2021/4/15
 */
public class MyStatistic {

    /**
     * 定義正則表達(dá)式匹配單詞
     */
    private static Pattern PATTERN = Pattern.compile("[a-zA-Z]+");

    /**
     * Java常用關(guān)鍵字?jǐn)?shù)組
     */
    private static String[] JAVA_KEYWORD_ARRAY = {"abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "extends", "false", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "void", "volatile", "while"};


    /**
     * 返回結(jié)果為文件中包含的出現(xiàn)頻率最高的3個(gè)Java關(guān)鍵字
     *
     * @param filePath
     * @return
     * @throws IOException
     */
    public String[] topJavaWords(String filePath) throws IOException {

        // 讀取文件
        String str = readFileToString(filePath);

        // 使用正則表達(dá)式,判斷是否是一個(gè)單詞
        Matcher matcher = PATTERN.matcher(str);

        // 統(tǒng)計(jì)關(guān)鍵字出現(xiàn)的次數(shù)
        Map<String, Integer> map = timesKeyWord(matcher);
        System.out.println("統(tǒng)計(jì)結(jié)果 ->" + map);

        // 對統(tǒng)計(jì)結(jié)果排序
        List<Map.Entry<String, Integer>> sortList = sort(map);

        return top(sortList, 3);
    }

    /**
     * 讀取文件
     *
     * @return
     */
    public static String readFileToString(String filePath) {
        String str = null;
        try {
            BufferedReader reader = new BufferedReader(new FileReader(filePath));
            StringBuffer buffer = new StringBuffer();
            String line = null;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            reader.close();
            // 整個(gè)文件的內(nèi)容 轉(zhuǎn)成 String 類型
            str = buffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * 判斷是否是Java關(guān)鍵字
     *
     * @param keyword
     * @return
     */
    public static boolean isJavaKeyWord(String keyword) {
        return (Arrays.binarySearch(JAVA_KEYWORD_ARRAY, keyword) >= 0);
    }

    /**
     * 統(tǒng)計(jì)關(guān)鍵字出現(xiàn)的次數(shù)
     *
     * @param matcher
     * @return
     */
    public static Map<String, Integer> timesKeyWord(Matcher matcher) {
        // 用一個(gè)集合存放統(tǒng)計(jì)結(jié)果 key = 關(guān)鍵字 value = 出現(xiàn)的次數(shù)
        Map<String, Integer> map = new TreeMap<>();

        String word = "";
        // 出現(xiàn)次數(shù) 默認(rèn)第一次
        int times = 1;
        while (matcher.find()) {
            word = matcher.group();
            System.out.println("拿到單詞 -> " + word);
            // 判斷是否使java關(guān)鍵字
            if (isJavaKeyWord(word)) {
                System.out.println(word + " 是關(guān)鍵字");
                // 如果包含該鍵,單詞出現(xiàn)過
                if (map.containsKey(word)) {
                    // 得到單詞出現(xiàn)的次數(shù)
                    times = map.get(word);
                    // 出現(xiàn)的次數(shù) + 1
                    map.put(word, times + 1);
                } else {
                    // 否則單詞第一次出現(xiàn),添加到集合中,出現(xiàn)次數(shù) = 1
                    map.put(word, times);
                }
            }
        }
        return map;
    }

    /**
     * 排序
     *
     * @param map
     * @return
     */
    public static List<Map.Entry<String, Integer>> sort(Map<String, Integer> map) {
        List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            //降序排列
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });
        return list;
    }

    /**
     * 獲取出現(xiàn)次數(shù)高的關(guān)鍵字?jǐn)?shù)組
     *
     * @param list
     * @param topNum
     * @return
     */
    public static String[] top(List<Map.Entry<String, Integer>> list, int topNum) {
        String[] result = new String[topNum];
        for (int i = 0; i < result.length && i < list.size(); i++) {
            // 取降序排列后的前三個(gè) 就是出現(xiàn)次數(shù)最多的三個(gè)關(guān)鍵字
            result[i] = list.get(i).getKey();
            System.out.println(list.get(i).getKey() + "出現(xiàn)了 " + list.get(i).getValue() + " 次");
        }
        return result;
    }


    public static void main(String[] args) {
        MyStatistic myStatistic = new MyStatistic();
        try {
            // 參數(shù)是任意一個(gè)文件的全路徑,我這里寫的是當(dāng)前這個(gè)文件
            String[] strArray = myStatistic.topJavaWords("E:\\IdeaProjects\\xxxxxx\\src\\test\\java\\com\\ioword\\MyStatistic.java");
            System.out.println("topJavaWords 執(zhí)行結(jié)果 " + JSON.toJSONString(strArray));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
  • 執(zhí)行結(jié)果

怎么用Java讀取文件統(tǒng)計(jì)返回文件中包含的出現(xiàn)頻率最高的3個(gè)Java關(guān)鍵字

到此,關(guān)于“怎么用Java讀取文件統(tǒng)計(jì)返回文件中包含的出現(xiàn)頻率最高的3個(gè)Java關(guān)鍵字”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI