package xFTest;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import junit.framework.TestCase;
public class TextTest extends TestCase{
@Test
public void test(){
try{
String encoding="GBK";
File file=new File("E://test.txt");
if(file.isFile() && file.exists()){ //判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file),encoding);//考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
HashMap<String ,Integer> has = new HashMap<String ,Integer> ();
while((lineTxt = bufferedReader.readLine()) != null){
HashMap<String ,Integer> hasMap = this.StatList(lineTxt);
this.statMap(has, hasMap);
}
read.close();
List<Map.Entry<String, Integer>> list = this.sortMap(has);
this.printMap(list);
}else{
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
}
/**
* 对数组解析,将单词和数存入到map中
* @param str
* @return
*/
public HashMap<String ,Integer> StatList(String str) {
HashMap<String ,Integer> has = new HashMap<String ,Integer> (); // 打开一个哈希表
String[] slist = str.split(" ");
for (int i = 0; i < slist.length; i++) {
if (!has.containsKey(slist[i])) { // 若尚无此单词
has.put(slist[i], 1);
} else {//如果有,就在将次数加1
has.put(slist[i],has.get(slist[i])+1 );
}
}
return has;
}
/**
* 对map进行重新赋值
* @param has
* @param hasMap
* @return
*/
public HashMap<String,Integer> statMap(HashMap<String ,Integer> has, HashMap<String ,Integer> hasMap){
Iterator iterator = hasMap.keySet().iterator();
while(iterator.hasNext()){
String word = (String) iterator.next();
if (!has.containsKey(word)) { // 若尚无此单词
has.put(word, 1);
} else {//如果有,就在将次数加1
has.put(word,has.get(word)+1 );
}
}
return has;
}
/**
* 对map进行排序
* @param has
* @return
*/
public List<Map.Entry<String, Integer>> sortMap(HashMap<String ,Integer> has){
List<Map.Entry<String, Integer>> infoIds =
new ArrayList<Map.Entry<String, Integer>>(has.entrySet());
Collections.sort(infoIds, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return (o2.getValue() - o1.getValue()); //按value排序
//return (o1.getKey()).toString().compareTo(o2.getKey());
}
});
return infoIds;
}
/**
* 打印输出结果
* @param list
*/
public void printMap(List<Map.Entry<String, Integer>> list){
for(int i = 0 ; i <list.size();i++){
System.out.println("单词:"+list.get(i).toString());
}
}
}
最近下载更多
最近浏览更多
1waxzsq212345 LV2
2024年1月16日
interface LV22
2023年7月9日
xv123456 LV1
2023年6月1日
微信网友_6040315240812544 LV8
2022年10月31日
idm_Sure LV3
2022年5月13日
微信网友_5937326340837376
2022年4月29日
暂无贡献等级
2898369623 LV1
2021年10月12日
huaua7676 LV30
2021年9月2日
mengfanyun LV9
2021年6月18日
20210119yiyi
2021年1月19日
暂无贡献等级

