运用 HashMap统计文章单词
使用 HashMap统计文章单词
package johney; /** * 该项止主要查找英语文章中统计出现的单词和次数 */ import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Set; public class MyHashMap { /** * @param args */ static HashMap<String, Integer> map; File file; static String pathname = "abc.txt"; static FileInputStream fis; static String word;// 用来存放抒情诗字符 static Set set; static Iterator iterator; static char temp; static int count; static int i = 0; static int number = 1; static boolean state = false; public static void main(String[] args) { // TODO Auto-generated method stub map = new HashMap<String, Integer>(); File file = new File(pathname); try { fis = new FileInputStream(file); // System.out.println("The file is exists!"); count = fis.read(); // 文件未读完 while (count != -1) { // 转为字符 temp = (char) count; // 若为字母 if ((temp >= 'a' && temp <= 'z') || (temp >= 'A' && temp <= 'Z')) { word = word + temp; state = true; // System.out.println(word); } // 若不为字符 else if (state){ // 若单词已经存在在映射表map中 if (word !=" ") { if (map.containsKey(word)) { number = map.get(word); number++; map.put(word, number); number = 1; } else { map.put(word, number); } state = false; } word = " "; } // 根据文件格式进行处理 count = fis.read(); count = fis.read(); } // 关闭读写流及文件 fis.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 输出map的内容 // 获取全部键 set = map.keySet(); iterator = set.iterator(); while (iterator.hasNext()) { word = (String) iterator.next(); number = map.get(word); System.out.println(word + ":" + number); } } }