0

StringUtils.countMatches用来计算单词频率,有没有办法在文本中搜索以某些字符开头的单词?

例子:

在“我的公寓里的人工艺术”中搜索艺术将返回 3!我需要它为仅以艺术开头的单词返回 2 。

我的解决方案是用空格替换文本中的 \r 和 \n 并将代码修改为:

text = text.replaceAll("(\r\n|\n)"," ").toLowerCase();
searchWord = " "+searchWord.toLowerCase();
StringUtils.countMatches(text, searchWord);

我还尝试了以下正则表达式:

patternString = "\\b(" + searchWord.toLowerCase().trim() + "([a-zA-Z]*))";
pattern = Pattern.compile(patternString);
matcher = pattern.matcher(text.toLowerCase());

问题:-我的第一个解决方案有意义还是有更好的方法来做到这一点?

- 我的第二个解决方案更快吗?因为我正在处理大型文本文件和相当数量的搜索词。

谢谢

4

2 回答 2

3
text = text.replaceAll("(\r\n|\n)"," ").toLowerCase();
searchWord = " "+searchWord.toLowerCase();
String[] words = text.split(" ");
int count = 0;
for(String word : words)
   if(searchWord.length() < word.length())
        if(word.substring(word.length).equals(searchWord))
            count++;

循环提供相同的效果。

于 2014-06-18T15:00:46.943 回答
2

使用正则表达式计算art.... 使用的模式是:

\b<search-word>

在这里,\b匹配一个单词边界。当然,\b在模式字符串中列出时需要进行转义。下面是一个例子:

String input = "artificial art in my apartment";
Matcher matcher = Pattern.compile("\\bart").matcher(input);

int count = 0;
while (matcher.find()) {
    count++;
}

System.out.println(count);

输出:2

于 2014-06-18T15:04:27.640 回答