-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.java
66 lines (57 loc) · 2.17 KB
/
main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class Test {
private static String path = "English.txt";
public static void main(String[] args) throws IOException {
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
int thechar;
StringBuffer sb = new StringBuffer();
HashMap<String, Integer> wordList = new HashMap<String, Integer>();
while ((thechar = isr.read()) != -1) {
char letter = (char) thechar;
if ((letter >= 'a' && letter <= 'z')
|| (letter >= 'A' && letter <= 'Z')) {
sb.append(letter);
} else if (sb.length() != 0) {
String theword = new String(sb);
if (wordList.containsKey(theword)) {
wordList.put(theword, wordList.get(theword) + 1);
} else {
wordList.put(theword, 1);
}
sb.delete(0, sb.length());
}
}
isr.close();
List<Map.Entry<String, Integer>> words = new ArrayList<Map.Entry<String, Integer>>(
wordList.entrySet());
Collections.sort(words, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> o1,
Entry<String, Integer> o2) {
return -(o1.getValue() - o2.getValue());
}
});
System.out.println("读取的文件中出现频率最多的十个单词是:");
int i = 0;
for (Map.Entry<String, Integer> node : words) {
if (i < 10) {
System.out.println(node.getKey() + " : " + node.getValue());
} else {
break;
}
i++;
}
}
}