1 Star 0 Fork 0

沈梦然/22李爽_21沈梦然_实训一

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
Wordstatistics.java 2.32 KB
一键复制 编辑 原始数据 按行查看 历史
沈梦然 提交于 7年前 . 词频统计
package com.example.shea.goldenpoint2rd;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
// 实现从文件中读入英文文章,统计单词个数,并对于结果进行排序处理
public class Wordstatistics {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("F:\\hhh\\1.txt")); //读取文件路径
List<String> lists = new ArrayList<String>(); //存储过滤后单词的列表
String readLine = null;
while((readLine = br.readLine()) != null){
String[] wordsArr1 = readLine.split("[^a-zA-Z]"); //过滤出只含有字母的
for (String word : wordsArr1) {
if(word.length() != 0){ //去除长度为0的行
lists.add(word);
}
}
}
br.close();
Map<String, Integer> wordsCount = new TreeMap<String,Integer>(); //存储单词计数信息,key值为单词,value为单词数
//单词的词频统计
for (String li : lists) {
if(wordsCount.get(li) != null){
wordsCount.put(li,wordsCount.get(li) + 1);
}else{
wordsCount.put(li,1);
}
}
SortMap(wordsCount); //按值进行排序
}
//按value的大小进行排序
public static void SortMap(Map<String,Integer> oldmap){
ArrayList<Map.Entry<String,Integer>> list = new ArrayList<Map.Entry<String,Integer>>(oldmap.entrySet());
Collections.sort(list,new Comparator<Map.Entry<String,Integer>>(){
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o2.getValue() - o1.getValue(); //降序排列
}
});
for(int i = 0; i<list.size(); i++){
System.out.println(list.get(i).getKey()+ ": " +list.get(i).getValue());
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/smr_777/Wordstatistics.git
git@gitee.com:smr_777/Wordstatistics.git
smr_777
Wordstatistics
22李爽_21沈梦然_实训一
master

搜索帮助