java读取txt里面的汉词字符串,记录每个汉词(不是单个字符)出现的次数,并输出,请问怎么实现

2024-12-15 23:59:19
推荐回答(2个)
回答1:

1.你的需求是txt中,每行一个汉词没有其他内容吗?

2.最后输出txt中包含哪些汉字和他们的个数?


是这样的吗?

示例

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class ReaderTxt {
    /**
     * @Description:读取文件,并记录汉词及次数
     * @param path - 文件地址
     * @return
     * @throws
     */
    public static Map getFileContent(String path) {
        Map map = new HashMap();
        File file = new File(path);
        InputStreamReader read = null;
        BufferedReader reader = null;
        try {
            read = new InputStreamReader(new FileInputStream(file), "gbk");
            reader = new BufferedReader(read);
            String line;
            while ((line = reader.readLine()) != null) {
                if (map.containsKey(line)) {
                    int value = map.get(line) + 1;
                    map.put(line, value);
                } else {
                    map.put(line, 1);
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (read != null) {
                try {
                    read.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return map;
    }
    public static void main(String[] args) {
        Map map = ReaderTxt.getFileContent("d:/data.txt");
        Set keys = map.keySet();
        for (Iterator it = keys.iterator(); it.hasNext();) {
            String key = it.next();
            System.out.print("汉词:" + key);
            System.out.println(",出现次数:" + map.get(key));
        }
    }
}

回答2:

用一个HashMap,每次取一个汗词a,如果map.contains(a),那么map.geta(a).++;否则map.put(a,1)