public static void main(String[] args) {
// TODO Auto-generated method stub
//用HashMap来存储《单词:词频》这样一个映射关系
HashMap<String,Integer>hasMap = new HashMap<>();
//用正则表达式来过滤字符串的所有标点符号
String regex ="[【】、.。,\"!--;:?\'\\]]";
try{
BufferedReader br = new BufferedReader(new FileReader("F:\\text.txt"));
String value;
while((value=br.readLine())!=null){
value = value.replaceAll(regex," ");
StringTokenizer tokenizer = new StringTokenizer(value);
while(tokenizer.hasMoreTokens()){
String word = tokenizer.nextToken();
if(!hasMap.containsKey(word)){
hasMap.put(word,new Integer(1));
}else{
int k = hasMap.get(word)+1;
hasMap.put(word, new Integer(k));
}
}
}
//遍历HasMap,输出结果
Iterator it = hasMap.keySet().iterator();
while(it.hasNext()){
String word = (String)it.next();
System.out.println(word +":\t"+hasMap.get(word));
}
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
java实现词频统计程序
最新推荐文章于 2022-06-02 16:53:06 发布