统计文本字数

 package textpackage;
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
/*
 查找hello.txt文件中的数据
 */
class Word
{
 public String word="";
 public int count=0;
 public Word()
 {
 word="";
 count=0;
 }
}
public class Class3 extends Frame  {
    public String[] getWords()  //获取单词
  {
    try
    {
     RandomAccessFile in=new RandomAccessFile("Hello.txt","rw");
     String source,s;
     source="";
     while((s=in.readLine())!=null)
     source=source+s;
     String temp[]=source.split("[' ',.;!]"); //过滤单词,每个单词存放在temp数组中
     return temp;
    }
    catch(IOException ex)
    {
     System.out.println(ex.toString());
     return null;
   }
  }
  public static void main(String args[])
  {
    Class3 test=new Class3() ;
   String s[]=test.getWords();
   Word[] w=new Word[s.length];
   int i,j=0;
   for(i=0;i<w.length;i++) //对象初始化
     w[i]=new Word();
   while(j><s.length)
   { for(i=0;i<w.length && w[i].count>0 ;i++)
     if(s[j].equals(w[i].word)==true)
      { w[i].count ++;
        break;
      }
      if(w[i].count ==0)
       { w[i].word=s[j];w[i].count++;}
     j++;
   }
   //排序
   Word wTemp=new Word();
   j=0;
   while(j<w.length)
   {
     for(i=j+1;i<w.length &&w[i].count>0;i++)
       if (w[j].count<w[i].count)
       {
         wTemp=w[j];
         w[j]=w[i];
         w[i]=wTemp;
       }
     j++;
   }
   System.out.println("单词总数:"+i);
   //输出结果
   for(i=0;i<w.length && w[i].count>0;i++)
     System.out.print(w[i].word+"次数"+w[i].count+ "  " );
 
  }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值