统计一篇文章中出现频率最高的汉字,java

import java.io.*;
import java.util.regex.*;

public class Mine {
 static String[] words=new String[1500];//保存汉字
 static int[] times=new int[1500];//保存相应汉字的出现次数
 static int index=0;
 
 public static void main(String[] args) throws Exception{
  readByChar();
  int temp=0;
  int number=0;
  //选择出times数组中最大的数字,即某汉字的最大频率
  for(int i=0;i<index;i++){
   if(temp<times[i]){
    temp=times[i];
    number=i;
   }
  }
  System.out.println("最大频率汉字是:"+words[number]);
  System.out.println("频率为:"+(times[number]+1));
 }
 
 
 public static void readByChar()throws Exception{
  Reader r = new FileReader(new File("C:/Users/softwware/Desktop/test.txt"));
  int data = -1;
  while((data = r.read())!=-1){
   char c = (char)data;
   String str = String.valueOf(c);
   str = str.replaceAll("[\\pP‘’“”]", "");//过滤掉字符
   if(!isNumeric(str)){ //过滤掉数字
    int judge=0;//judge=0的话说明本字符还未出现过
    for(int i=0;i<index;i++){
     if(words[i].equals(str)){
      times[i]++;
      judge=1;
     }
    }
    if(judge==0){//judge=0的话说明本字符还未出现过,加入words【】
     words[index]=str;
     index++;
    }
    words[index]=str;
   }
  }
  r.close();
 }
 
 //判断是否数字的方法
 public static boolean isNumeric(String str)  
 {  
        Pattern pattern = Pattern.compile("[0-9]*");  
        Matcher isNum = pattern.matcher(str);  
        if( !isNum.matches() ) {  
           return false;  
        }  
        return true;  
 }  

 public static void make() throws IOException{
 InputStream in = new FileInputStream("C:/Users/softwware/Desktop/test.txt");
 //in是别人传递过来
 //把字节输入流转变一下,变成字符操作方式
 Reader r = new InputStreamReader(in);
 BufferedReader br = new BufferedReader(r);
 String line = null;
 br.close();
 }
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值