统计文章单词个数-java

代码:

package test1;

import java.io.FileReader;
import java.io.IOException;

class Word{
	String value;
	int count;
	Word next;
	public Word(String s,int count) {
		this.value = s;
		this.count = count;
		next = null;
	}
	public Word() {
		this.value = "";
		this.count = 0;
		next = null;
	}	
}

public class CountWord {

	private static FileReader f;

	public static void main(String[] args) throws IOException {
		Word wd = new Word();
		Word list,newWord;
		String st = "";
		char[] ch = new char[1];
		boolean exist = false;
		f = new FileReader("C:/Users/admin/Desktop/File/n2.txt");
		
		while(f.read(ch)!=-1) {
			if(String.valueOf(ch).equals("\"")||String.valueOf(ch).equals(" ")||String.valueOf(ch).equals("\r")||String.valueOf(ch).equals("\n")||String.valueOf(ch).equals(".")||String.valueOf(ch).equals(",")||String.valueOf(ch).equals("'")) {
				list = wd;
				while(list!=null) {
					if(list.value.equalsIgnoreCase(st)) {
						list.count++;
						exist = true;
						break;
					}else {
						list = list.next;	
					}		
				}
				if(exist==false) {
					newWord = new Word(st,1);
					newWord.next = wd.next;
					wd.next = newWord;
				}else {
					exist = false;					
				}
				st = "";
			}else {
				st+=String.valueOf(ch);
			}
	    }
		System.out.println("前5个出现频率最高的单词为:");
		for(int i=1;i<=5;i++) {
			Word w = new Word("",0);
			for(list =wd.next;list!=null;list=list.next) {
				if(list.count>w.count) {
					w = list;
				}				
			}	
			
			System.out.println("第"+i+"个"+w.value+"个数为"+w.count);
			
			for(list =wd;list.next!=w;list=list.next);
			list.next=list.next.next;
		}
		f.close();
	}
}

图片:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值