-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountWordTest.txt
More file actions
48 lines (39 loc) · 1.49 KB
/
CountWordTest.txt
File metadata and controls
48 lines (39 loc) · 1.49 KB
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
package test;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class CountWord {
public static void main(String[] args) throws FileNotFoundException {
// 判断文件是否为空
// File file = new File("If not now when if not me who ");
File file = new File("ThreadPoolDemo.txt");
// 扫描器
Scanner scanner = new Scanner(file);
// 创建哈希表
HashMap<String, Integer> hashTable = new HashMap<String, Integer>();
while (scanner.hasNextLine()) {
String lineString = scanner.nextLine();
// 正则匹配非单词字符,分割为一个个的单词,组成字符数组
String[] wordArray = lineString.split("\\W+");
Set<String> wordSet = hashTable.keySet();
for (String s : wordArray) {
// 如果存在
if (wordSet.contains(s)) {
Integer count = hashTable.get(s);
count++;
hashTable.put(s, count);
} else {
hashTable.put(s, 1);
}
}
}
System.out.println("-------------------");
// 遍历hashTable 打印: 单词 出现次数
for (Map.Entry<String, Integer> entry : hashTable.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
}