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

最好有eclipse代码写出来,复制只要成功的也行。另外,txt里面每行只有一个汉词,但有很多行

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<String, Integer> getFileContent(String path) {
        Map<String, Integer> map = new HashMap<String, Integer>();
        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<String, Integer> map = ReaderTxt.getFileContent("d:/data.txt");
        Set<String> keys = map.keySet();
        for (Iterator<String> it = keys.iterator(); it.hasNext();) {
            String key = it.next();
            System.out.print("汉词:" + key);
            System.out.println(",出现次数:" + map.get(key));
        }
    }
}

追问

最后输出是汉词,和他们的个数,而不是单单一个汉字的个数

追答

示例贴上面了,自己看下!~
有问题再追问,good luck!

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-05-14
用一个HashMap<String,Integer>,每次取一个汗词a,如果map.contains(a),那么map.geta(a).++;否则map.put(a,1)追问

嗯嗯,我也去试下你的方法,谢谢哈~

相似回答