JAVA实现统计文件中每个单词出现的次数

public class splitWords
{
	static HashMap<String, Integer > hashMap=new HashMap<String,Integer>();
	
	public static void main(String[] args) throws FileNotFoundException
	{
		splitWords sw=new splitWords();
		sw.count("C:/Users/10467/Desktop/file1.txt");
		sw.count("C:/Users/10467/Desktop/file2.txt");
		sw.result();
	}
	public void count(String src) throws FileNotFoundException {
		File file=new File(src);
		if(!file.exists())
		{
			System.out.println("文件不存在");
			return;
		}
		Scanner scanner=new Scanner(file);
		System.out.println(src+"----------------中的文章内容-------------------");
		while(scanner.hasNextLine())
		{
			String line=scanner.nextLine();
			System.out.println(line);
			//\w+ : 匹配所有的单词
			//\W+ : 匹配所有非单词
			String[] lineWords=line.split("\\W+");//用非单词符来做分割,分割出来的就是一个个单词
			
			Set<String> wordSet=hashMap.keySet();
			for(int i=0;i<lineWords.length;i++)
			{
				//如果已经有这个单词了,
				if(wordSet.contains(lineWords[i]))
				{
					Integer number=hashMap.get(lineWords[i]);
					number++;
					hashMap.put(lineWords[i], number);
				}
				else 
				{
					hashMap.put(lineWords[i], 1);
				}
			}
			
		}
		System.out.println("这个文件统计结束");
	}
	
	public void result() {
		System.out.println("-----------统计单词完成,所有文件单词总数为-------------------");
		Iterator<String> iterator=hashMap.keySet().iterator();
		while(iterator.hasNext())
		{
			String word=iterator.next();
//			System.out.printf("单词: "+word+"出现次数:"+hashMap.get(word));
			System.out.printf("单词:%-12s 出现次数:%d\n",word,hashMap.get(word));
		}
	}
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值