我试图使用Java扫描仪hasNext
方法,但我得到了奇怪的结果。也许我的问题很明显,但为什么这个简单的简单表达式"[a-zA-Z']+"
不适用于这样的词语:“分,任何事,主管”。我也试过这个"[\\w']+"
。Java扫描器hasNext(字符串)方法有时不匹配
public HashMap<String, Integer> getDocumentWordStructureFromPath(File file) {
HashMap<String, Integer> dictionary = new HashMap<>();
try {
Scanner lineScanner = new Scanner(file);
while (lineScanner.hasNextLine()) {
Scanner scanner = new Scanner(lineScanner.nextLine());
while (scanner.hasNext("[\\w']+")) {
String word = scanner.next().toLowerCase();
if (word.length() > 2) {
int count = dictionary.containsKey(word) ? dictionary.get(word).intValue() + 1 : 1;
dictionary.put(word, new Integer(count));
}
}
scanner.close();
}
//scanner.useDelimiter(DELIMITER);
lineScanner.close();
return dictionary;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
非常感谢@Angel Rodriguez这是一个很好的解决方案,但我不知道为什么不与hasnext(String)函数一起工作。 – flatronka 2013-04-07 18:02:34
好吧,我明白了你的意思,我已经编辑过......我解释了为什么它不起作用......希望它有助于... – 2013-04-07 18:35:39
非常感谢你我已经得到了它。非常感谢您的帮助。 +1进行详细解释。 – flatronka 2013-04-07 23:00:24