使用 HashMap统计文章单词

来源:互联网 发布:猫云seo seojsc 编辑:程序博客网 时间:2024/06/06 00:46
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 stubmap = 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 blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}// 输出map的内容// 获取全部键set = map.keySet();iterator = set.iterator();while (iterator.hasNext()) {word = (String) iterator.next();number = map.get(word);System.out.println(word + ":" + number);}}}
原创粉丝点击