统计英语单词

使用Scanner类和正则表达式统计一篇英文中的单词,要求如下:

1、一共出现了多少个单词。

2、有多少个互不相同的单词。

3、按单词出现的频率大小输出单词。

package 第七次;
import java.util.*;
import java.io.*;
import java.util.regex.*;

public class word {
    public static void main(String[] args) {

        String inputFile = "src/java线上作业/第三章/crossion.txt";// 读取输入文件

         Map<String,Integer> wordIndex = new HashMap<>();

        //设置set集合来存放已经出现的单词
        Set<String> Words = new HashSet<>();

        //单词计数器
        int count =0;

        //互不相同单词出现的次数
        int uncount =0;
        //定义集合用于存放互不相同的单词
        Map<Integer,String> dict;

        try (BufferedReader reader = new BufferedReader(new FileReader(inputFile))) {//new一个BufferedReader对象,将文件内容读取到缓存

            String line;

            while ((line = reader.readLine()) != null) {
                //读取无论是大写还是小写的单词
                Pattern pattern = Pattern.compile("[A-Za-z][A-Za-z-]*");//正则表达式,按先大写后小写

                Matcher matcher = pattern.matcher(line);

                while (matcher.find()) {

                    String word = matcher.group().toLowerCase();// 将单词转换为小写

                    wordIndex.put(word,wordIndex.getOrDefault(word,0)+1);

                    count++;

                    //输出不相同的单词,
                    if(!Words.contains(word)){

                        dict = new HashMap<>();

                        dict.put(count,word);

                        //3、将互不相同的单词以集合的方式输出
                        System.out.println(dict);

                        //将出现过的单词添加到集合中
                        Words.add(word);

                        uncount++;
                    }

                }

            }

            //1、互不相同单词出现的次数
            System.out.print("不相同的单词次数:"+uncount);

            //2、单词出现的数量
            System.out.print("单词出现的数量:"+count);

        }

        catch (IOException e) {

            e.printStackTrace();

        }
        //计算不同单词出现的次数
        List<Map.Entry<String, Integer>> sortedWords = new ArrayList<>(wordIndex.entrySet());

        Collections.sort(sortedWords, Map.Entry.<String, Integer>comparingByValue().reversed());

        for (Map.Entry<String, Integer> entry : sortedWords) {

                int countvalue = Integer.valueOf(entry.getValue());
                //输出
            System.out.println("单词出现的频率:"+entry.getKey() + ": " + countvalue*0.01+"%");
        }

    }
}

你可能感兴趣的:(c#,开发语言,java)