统计英语单词

使用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+"%");
        }

    }
}
  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值