我有一种在文本中搜索单词的方法,均由参数插入。
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;
}
如何插入多个单词并返回它们的出现?
,因此第一个也是最简单的选择是使用您的实际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: "bab|bbb|bcb|bdb|beb"
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()
。
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;
}