词频

要求:

(1). 实现一个控制台程序,给定一段英文字符串,统计其中各个英文单词(4字符以上含4字符)的出现频率。 附加要求:读入一段文本文件,统计该文本文件中单词的频率。

(2). 性能分析:

通过百度等搜索软件,可得到一些启发

预计完成时间:一天,实际:两天

git:https://github.com/775320358/list

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.Map.Entry;//需要用到的库
 
public class project {
 
    public static void main(String arg[]) {
 
        Map<String, Integer> map = new HashMap<String, Integer>();//用于通缉各个单词的词频
        String sentence = "Word is case insensitive, i.e. “file”, “FILE” and “File” are considered the same word.";//输入句子
        sentence = sentence.toLowerCase();//大小写转变
        StringTokenizer token = new StringTokenizer(sentence); 
 
        while (token.hasMoreTokens()) {
            String word = token.nextToken(", “”?.!:\"\"''\n"); //用标点隔开
            int count;
            if (map.containsKey(word))
            {
                count = map.get(word);
                map.put(word, count + 1); 
            } else
                map.put(word, 1); //统计词频
        }
        sort(map);
    }
 
    public static void sort(Map<String, Integer> map) {
        List<Map.Entry<String, Integer>> infoIds = new ArrayList<Map.Entry<String, Integer>>(
                map.entrySet());
        for (int i = 0; i < infoIds.size(); i++) { //输出
            Entry<String, Integer> id = infoIds.get(i);
            if (id.getKey().length() >= 4) 
            {//当字符大于4时输出
                System.out.println(id.getKey() + ":" + id.getValue());
            }
 
        }
 
    }
}

 

posted @ 2016-03-16 14:29  钱佳晨  阅读(258)  评论(5)    收藏  举报