我有一种方法来搜索文本中的单词,两者均由参数插入。
public Integer findTheWord(String stringToCheck, String regexString) throws IOException {
int count = 0;
Pattern regexp = Pattern.compile("\\b" + regexString + "\\b");
Matcher matcher = regexp.matcher(stringToCheck);
while (matcher.find()) {
count++;
String matchString = matcher.group();
System.out.println(matchString);
}
System.out.println(count);
return count;
}
如何插入多个单词并返回每个单词的出现次数?
答案 0 :(得分:1)
HashMap作为参数,输入字符串为键,正则表达式为值,遍历所有条目,执行您的方法,并返回一个与单词匹配的HashMap作为键,出现次数为值。
public HashMap<String, Integer> findTheWordsAndOccurences(HashMap<String, String> stringsAndRegex) throws IOException {
HashMap<String, Integer> result = null;
for (Map.Entry<String, String> entry : stringsAndRegex.entrySet()){
String stringToCheck = entry.getKey();
String regexString = entry.getValue();
String matchString = "";
int count = 0;
Pattern regexp = Pattern.compile("\\b" + regexString + "\\b");
Matcher matcher = regexp.matcher(stringToCheck);
while (matcher.find()) {
count++;
matchString = matcher.group();
System.out.println(matchString);
result.put(matchString, count);
}
}
return result;
}
答案 1 :(得分:1)
第一个也是最简单的选择是使用实际的findTheWord()
方法并创建一个使用它的新方法:
public Map<String, Integer> findTheWords(String stringToCheck, List<String> words) {
return words.stream().distinct()
.collect(Collectors.toMap(Function.identity(), word -> findTheWord(stringToCheck, word)));
}
public Integer findTheWord(String stringToCheck, String regexString) {
Pattern regexp = Pattern.compile("\\b" + regexString + "\\b");
Matcher matcher = regexp.matcher(stringToCheck);
int count = 0;
while (matcher.find()) {
count++;
}
return count;
}
问题是如果您要使用大量单词查找和较大文本,因为它会在每个单词的给定字符串上进行迭代。因此,另一种方法是为所有单词创建一个正则表达式,并在结果映射中递增下一个找到的单词:
public Map<String, Integer> findTheWords(String stringToCheck, List<String> words) {
Pattern regexp = Pattern.compile(words.stream().distinct().map(word -> "\\b" + word + "\\b").collect(Collectors.joining("|")));
// creates a pattern like this: "\ba\b|\bb\b|\bc\b|\bd\b|\be\b"
Matcher matcher = regexp.matcher(stringToCheck);
Map<String, Integer> result = new HashMap<>();
while (matcher.find()) {
String word = matcher.group();
result.put(word, result.getOrDefault(word, 0) + 1);
}
return result;
}
此外,您可能会考虑使用Set
代替单词List
,因为这些值是唯一的,因此无需在流上调用.distinct()
。 / p>