【发布时间】:2018-05-05 22:44:14
【问题描述】:
我正在编写一个程序,它读取一个文本文件并计算每个单词出现的次数。程序应该输出比用户给出的某个阈值更频繁使用的单词。为了避免无聊的结果,我与提供的 100 个最常用的英语单词列表进行比较。
添加到 HashMap:
try {
// commonHashMap Filled
Scanner sc = new Scanner(new File("commonwords.txt"));
sc.useDelimiter("[^a-zA-Z']");
String str;
while (sc.hasNext()) {
str = sc.next().toLowerCase(Locale.ENGLISH);
commonHashMap.put(str, 1);
}
sc.close();
// bookHashMap Filled
sc = new Scanner(new File(book));
sc.useDelimiter("[^a-zA-Z']");
// Add the non-common words in the book to HashMap.
while(sc.hasNext()) {
str = sc.next().toLowerCase(Locale.ENGLISH);
if (!commonHashMap.containsKey(str)) {
if (bookHashMap.containsKey(str)) {
bookHashMap.put(str, bookHashMap.get(str)+1); }
else {
bookHashMap.put(str, 1); }
}
}
sc.close();
}
显示:
Iterator<Map.Entry<String, Integer>> iterator = bookHashSet.iterator();
while(iterator.hasNext()) {
Map.Entry<String, Integer> x = iterator.next();
if (iterator.hasNext()) {
String key = x.getKey();
int value = x.getValue();
if (value > thresholdValue) {
System.out.println(key + ": " + value);
}
}
}
输出:
1) "The Adventures of Tom Sawyer" by Mark Twain
2) "Tale of Two Cities" by Charles Dickens
3) "The Odyssey" by Homer
Choice Book: 1
Enter Threshold Value: 200
: 27213
don't: 222
tom: 695
huck: 224
me: 212
“27213”从何而来?
【问题讨论】:
-
尝试使用一个或多个非字母字符作为分隔符:
[^a-zA-Z']+ -
What does your step debugger tell you?。使用步进调试器可以非常快速轻松地回答您的问题。在使用 StackOverflow 之前,您应该始终尝试使用步进调试器解决您的问题。
标签: java regex hashmap hashset