使用 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);
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值