计算文件中特定String的出现次数 [英] counting the occurence of a particular String in a file
问题描述
以下是我所使用的代码:
Here's the code that I've worked upon:
while ((lineContents = tempFileReader.readLine()) != null)
{
String lineByLine = lineContents.replaceAll("/\\.", System.getProperty("line.separator")); //for matching /. and replacing it by new line
changer.write(lineByLine);
Pattern pattern = Pattern.compile("\\r?\\n"); //Find new line
Matcher matcher = pattern.matcher(lineByLine);
while(matcher.find())
{
Pattern tagFinder = Pattern.compile("word"); //Finding the word required
Matcher tagMatcher = tagFinder.matcher(lineByLine);
while(tagMatcher.find())
{
score++;
}
scoreTracker.add(score);
score = 0;
}
}
我的示例输入包含6行,其中出现 word
[0,1,0,3,0,0]
所以当我打印 scoreTracker
(这是 ArrayList
)我想要上面的输出。
但是,我得到 [4,4,4,4,4,4]
这是字的总出现次数
,但不是逐行的。
请帮忙。
My sample input contains 6 lines, with occurences of word
being [0,1,0,3,0,0]
So when I print scoreTracker
(which is an ArrayList
) I want the above output.
But instead, I get [4,4,4,4,4,4]
which it the total occurence of the word
, but not line by line.
Kindly help.
推荐答案
lineByLine
指向整个你文件的内容。这就是你得到 [4,4,4,4,4,4]
的原因。您需要将每一行存储在另一个变量行
中,然后使用 tagFinder.find(line)
。
最终代码将如下所示
lineByLine
points to the entire contents of your file. That is the reason you are getting [4,4,4,4,4,4]
. You need to store each line in another variable line
and then use tagFinder.find(line)
.
Final code will look like this
while ((lineContents = tempFileReader.readLine()) != null)
{
String lineByLine = lineContents.replaceAll("/\\.", System.getProperty("line.separator")); //for matching /. and replacing it by new line
changer.write(lineByLine);
Pattern pattern = Pattern.compile(".*\\r?\\n"); //Find new line
Matcher matcher = pattern.matcher(lineByLine);
while(matcher.find())
{
Pattern tagFinder = Pattern.compile("word"); //Finding the word required
//matcher.group() returns the input subsequence matched by the previous match.
Matcher tagMatcher = tagFinder.matcher(matcher.group());
while(tagMatcher.find())
{
score++;
}
scoreTracker.add(score);
score = 0;
}
}
这篇关于计算文件中特定String的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!