找一篇文章中里面指定单词的个数

给大家推荐个靠谱的公众号程序员探索之路,大家一起加油https://i-blog.csdnimg.cn/blog_migrate/93320939ba8f8b0a898e29429753f496.png

import java.io.*;
import java.util.*;
public class SearchWordTimes {

	/**先调用  读取文件方法  然后  记录  方法  然后 打印方法
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		File file =new File("file/qfile.txt");
		HashMap<String,Integer> map = new HashMap<String,Integer>();
		Set<String> set = new HashSet<String>();
		String[] str = read(file).split(" ");
		record(map,set,str);
		print(map);
	}
	/**
	 * 将 file路径下的文件读出来
	 * @param file
	 * @return 返回读出来的文件内容的字符串形式
	 * @throws IOException
	 */
	public static String read(File file) throws IOException{
		BufferedReader read = new BufferedReader(new FileReader(file));
		StringBuffer str = new StringBuffer();
		String s = null;
		while((s = read.readLine()) != null){
			str.append(s);
		}
		return str.toString();
	}
	/**
	 * 将传进来的字符串数组   检测处每个单词出现了多少次  map的键是单词  值是次数
	 * 注意:由于开头字母大写 与不大写的单词 是同一个单词 那么 都转换为小写的处理
	 * 如果 单词  能够 存进 set集合中 那么就是 一个 新的单词 出现的次数就是 1  如果不能说明 是出现过的单词 
	 * 那么就把 对应的值取出来   删除带健值对  次数加1 重新存入
	 * 特殊单词  就是 后面加's的单词  这是 两个单词  需要 单独处理
	 * @param map
	 * @param set  
	 * @param str
	 */
	public static void record(HashMap map,Set set,String[] str){
		for(int i = 0;i < str.length;i++){
			str[i] = change(str[i]);
			//单独处理
			if(str[i].length() > 1&&Character.toString(str[i].charAt(str[i].length() - 2)).equals("'")){
				str[i] = str[i].substring(0,str[i].length() - 2);
				if(set.add("is")){
					map.put("is", 1);
				}else{
					int num =(Integer)map.get("is") + 1;
					map.remove("is");
					map.put("is", num);
					//System.out.println("is = " + num);
				}
			}
			
			if(set.add(str[i])){
				map.put(str[i], 1);
				//System.out.println(str[i] + 1);
			}else{
				int num =(Integer)map.get(str[i]) + 1;
				map.remove(str[i]);
				map.put(str[i], num);
				//System.out.println(str[i] + " = " +  num);
			}
		}
	}
	/**
	 * 检测str第一个字母是否大写如果是 那么把大写转换为小写
	 * @param str
	 */
	public static String change(String str){
		char ch = str.charAt(0);
		if(ch >= 'A'&&ch <= 'Z'){
			return str.replace(Character.toString(ch), Character.toString((char)(ch + 32)));
		}
		return str;
	}
	/*
	 * 输入单词 打印出现的次数
	 */
	public static void print(HashMap map){
		Scanner s = new Scanner(System.in);
		String str = s.next();
		str = change(str);
		if(map.get(str) == null){
			System.out.println("您输入单词不在文章中");
		}else{
			System.out.println(map.get(str));
		}
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值