我想分别在文本文件的每一行中查找并统计单词单元、设备、方法、模块的所有出现次数。这就是我所做的,但我不知道如何使用多个模式以及如何分别计算行中每个单词的出现次数?现在它只计算每一行所有单词的出现次数。提前致谢!
private void countPaterns() throws IOException {
Pattern nom = Pattern.compile("unit|device|method|module|material|process|system");
String str = null;
BufferedReader r = new BufferedReader(new FileReader("D:/test/test1.txt"));
while ((str = r.readLine()) != null) {
Matcher matcher = nom.matcher(str);
int countnomen = 0;
while (matcher.find()) {
countnomen++;
}
//intList.add(countnomen);
System.out.println(countnomen + " davon ist das Wort System");
}
r.close();
//return intList;
}
最佳答案
最好使用单词边界并使用 map 来记录每个匹配关键字的数量。
Pattern nom = Pattern.compile("\\b(unit|device|method|module|material|process|system)\\b");
String str = null;
BufferedReader r = new BufferedReader(new FileReader("D:/test/test1.txt"));
Map<String, Integer> counts = new HashMap<>();
while ((str = r.readLine()) != null) {
Matcher matcher = nom.matcher(str);
while (matcher.find()) {
String key = matcher.group(1);
int c = 0;
if (counts.containsKey(key))
c = counts.get(key);
counts.put(key, c+1)
}
}
r.close();
System.out.println(counts);
关于java - 如何将文本文件与多个正则表达式模式进行匹配并计算这些模式的出现次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33423994/