先创建一个随机词汇的文件 ,一会来统计
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Random;
public class Demo01 {
static String[] arr = {"面向对象", "封装", "继承", "多态"
, "数组", "父类", "抽象类", "接口", "异常", "运行时异常"
, "编译时异常", "抽象方法", "成员方法", "构造方法","静态方法"
,"成员变量", "局部变量", "静态变量", "常量", "重写", "重载"
, "向上转型", "向下转型"};
static Random random = new Random();
static String name = "D:\\io\\io2\\words";
public static void main(String[] args) {
try {
Writer out = new FileWriter(name);
for (int i = 1; i < 10000; i++) {
int index = random.nextInt(arr.length);
if(i % 10 == 0){
out.write(arr[index] + "\n");
}else {
out.write(arr[index] + " ");
}
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
词频统计
打印结果
完整源码
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class Demo02 {
public static void main(String[] args) {
HashMap<String,Integer> map = new HashMap<>();
TreeMap<Integer,String> treeMap = new TreeMap<>();
String name = "D:\\io\\io2\\words";
try {
Reader reader = new FileReader(name);
BufferedReader read = new BufferedReader(reader);
String line = null;
while((line = read.readLine()) != null){
String[] arr = line.split(" ");
for (String word : arr) {
if(map.get(word) == null){
map.put(word,1);
}else {
map.put(word,map.get(word)+1);
}
}
}
System.out.println("词频统计结果:");
Set<Map.Entry<String, Integer>> set = map.entrySet();
for (Map.Entry<String, Integer> entry :set) {
String key = entry.getKey();
Integer value = entry.getValue();
treeMap.put(value,key);
}
System.out.println("个数:单词");
treeMap.forEach((k,v) -> {
System.out.println(k + ":" + v);
});
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}