日期:2014-05-20  浏览次数:20815 次

谁能用JAVA帮我实现一段程序(是一道笔试题)
统计一篇英文文档中包含几个不同的单词 每个单词出现的频率是什么?
这是一道笔试题,单词怎么区分呢?真是想不明白 用空格拆分么?那出现频率怎么弄呢?

------解决方案--------------------
Java code
    public static void main(String[] args) {
        try {
            BufferedReader br = new BufferedReader(new FileReader("d:/123.txt"));//举个例子,假设D盘有一个叫做123的txt格式的英文文件
            StringBuffer sb = new StringBuffer();
            Set<String> singleSet = new HashSet<String>();
            String temp = br.readLine();
            while (null != temp) {//这里循环以行为单位不断读数据,存储在一个StringBuffer里
                sb.append(temp + " ");
                temp = br.readLine();
            }
            String[] a = sb.toString().split("[^A-Za-z0-9]");//把StringBuffer分解成String数组,以非字母和数字的任何字符分割
            for (String string : a) {//这里是个取巧的做法,要熟悉各种集合的区别,我用了HashSet,它是不允许加入重复数据的,我都加一遍,自然就剃重了。
                singleSet.add(string);
            }
            for (String childString : singleSet) {//此处判断出现多少次
                System.out.print(childString);
                int count = 0;
                for (String fatherString : a) {
                    if (fatherString.equals(childString)) {
                        count++;
                    }
                }
                System.out.println("出现" + count + "次");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

------解决方案--------------------
Java code

private Map<String, Integer> map =new HashMap<String, Integer>(); ;
    public static void main(String[] args) {
        Test test=new Test();
        String str="asdf b are you too b,too too too too. Are";
        
        test.split(str);
        System.out.println(test.map);
    }
    
    public  void split(String str){
        String[] strSplit=str.split("[, ;.!, ;。!]");//符号自己定义
        
        for(String string : strSplit){
            if(map.get(string)!=null){
                map.put(string, map.get(string)+1);
            }else{
                map.put(string, 1);
            }
        }
    }