题目一:写一个程序,用于分析一个字符串中各个单词出现的频率,并将单词和它出现的频率输出显示。
package test1;
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.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WordCount {
public void run() throws Exception {
long time1 = System.currentTimeMillis();
BufferedReader reader = new BufferedReader(new FileReader(
"D:\wordtest.txt"));
StringBuffer buffer = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
reader.close();
Pattern expression = Pattern.compile("[a-zA-Z]+");// 定义正则表达式匹配单词
String string = buffer.toString();
Matcher matcher = expression.matcher(string);//
Map<String, Integer> map = new TreeMap<String, Integer>();
String word = "";
int times = 0;
while (matcher.find()) {// 是否匹配单词
word = matcher.group();// 得到一个单词-树映射的键
if (map.containsKey(word)) {// 如果包含该键,单词出现过
times = map.get(word);// 得到单词出现的次数
map.put(word, times + 1);
} else {
map.put(word, 1);// 否则单词第一次出现,添加到映射中
}
}
/*
* 核心:如何按照TreeMap 的value排序而不是key排序.将Map.Entry放在集合里,重写比较器,在用
* Collections.sort(list, comparator);进行排序
*/
List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(
map.entrySet());
/*
* 重写比较器
* 取出单词个数(value)比较
*/
Comparator<Map.Entry<String, Integer>> comparator = new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> left,
Map.Entry<String, Integer> right) {
return (left.getValue()).compareTo(right.getValue());
}
};
Collections.sort(list, comparator);// 排序
// 打印
int last = list.size() - 1;
try{
for (int i = last; i > last-10; i--) {
String key = list.get(i).getKey();
Integer value = list.get(i).getValue();
System.out.print("Top"+i+" : ");
System.out.println(key + " " + value);
}
}catch(Exception e){
//System.out.println("");
}
long time2 = System.currentTimeMillis();
System.out.print("耗时:");
System.out.println(time2 - time1+"ms");
}
}
}
package test1;
import static org.junit.Assert.*;
import org.junit.Test;
public class WordCountTest {
@Test
public void test() throws Exception {
WordCount wordtest=new WordCount();
wordtest.run();
}
}
import java.util.Scanner;
public class StringDemo {
public void run(){
Scanner in=new Scanner(System.in);
while(true){
String s=in.nextLine();
if(s.equalsIgnoreCase("quit")){
System.exit(0);
}
String[] ss=s.split("\s+");
StringBuffer sb=new StringBuffer();
for (int i=ss.length-1;i>=0;i--){
sb.append(ss[i]+" ");
}
System.out.println(sb);
}
}
}
package test2;
import static org.junit.Assert.*;
import org.junit.Test;
public class StringDemoTest {
@Test
public void test() {
StringDemo stringdemo=new StringDemo();
stringdemo.run();
}
}