我有一个单词列表,比如:
- Spring Data
- Java
- C++
- Junit
而且我有一个非常大的文本文件或字符串。
对于我的每个单词列表中的单词,我需要找出在这个大字符串中找到该单词的出现次数?
我期望的结果是:
- Spring Data(10)
- Java(3)
- C++(6)
- Junit(0)
上面只是4个元素,但在我的情况下可能会达到几千个。我可以遍历每个元素并查找该字符串的计数,但不确定是否最佳解决方案考虑性能?你们能否为我提供一些关于找到这个问题的最佳方法的建议呢?
如果需要匹配包含空格的字符串,我倾向于循环遍历目标字符串列表,在文本中进行适当转义的正则表达式搜索,并记录正则表达式匹配的数量。
strings
的数量,例如:public static void main(String[] args) throws FileNotFoundException {
String s = "a b c d e f d g e a c v d a w s";
Map<String, Long> wordCount = Arrays.stream(s.split("\\s"))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(wordCount);
}
如果您不想使用流,可以这样做:
String s = "a b c d e f d g e a c v d a w s";
Map<String, Long> wordCount = new HashMap<>();
String[] words = s.split("\\s");
for (String word : words) {
Long count = wordCount.get(word);
if (count == null) {
count = 0L;
}
count = count + 1L;
wordCount.put(word, count);
}
System.out.println(wordCount);
count = 0L; wordCount.put(word, count + 1);
- Sky Kelsey
str.split("\\s+")
然后查看 word-frequency-count-java-8。 - Bohemian