[英]How to count the number of lines that a specific word occurs in a txt file?
我不确定这是否是足够的代码,但我正在阅读一个 txt 文件,我想弄清楚如何打印包含“hello”的行数。
我已经打印出包含“hello”的行,但我需要弄清楚如何计算这些行。
或者有没有一种方法可以将每个“hello”行放入一个数组,然后打印出数组长度,这也是行数?
..任何帮助,将不胜感激!
while((line = br.readLine()) != null) {
// splits each line into words
String tokens[] = line.split(" ");
for(int i= 0; i<tokens.length; i++){
if(words[i].equalsIgnoreCase("hello")){
System.out.println(line+"\n");
//the above line prints out each line that contains "hello", but how would I create a variable for the number of lines
}
}
}
只需创建一个向上计数的变量:
int count = 0;
while ((line = br.readLine()) != null) {
// splits each line into words
String tokens[] = line.split(" ");
for (int i = 0; i < tokens.length; i++) {
if (words[i].equalsIgnoreCase("hello")) {
System.out.println(line + "\n");
count++; // count 1 up
}
}
}
System.out.println("Number of lines containing 'hello': " + count);
另外,如果想查询某个单词是否在字符串中,可以使用String#contains
方法:
int count = 0;
while ((line = br.readLine()) != null) {
// check for "hello" in string, case-sensitive
if (line.contains("hello")) {
count ++;
}
}
如果你想忽略大小写,使用而不是line.contains("hello")
: line.toLowerCase().contains("hello")
虽然其他解决方案完全有效,但您可以轻松地将它变成一个单行,所以我觉得我至少应该发布它以进行比较。 见下文:
System.out.println(br.lines().filter(Pattern.compile("(?i)hello").asPredicate()).count());
这会得到一个 stream,其中 stream 中的每个元素都是来自 BufferedReader 的一行。 然后它过滤 stream 中包含“hello”的行。 (?i)
表示在正则表达式中不区分大小写。 然后它只是统计 stream 中剩余的元素个数,并打印出结果。 您还可以将结果存储在一个变量中并在以后使用它,如下所示:
long num = br.lines().filter(Pattern.compile("(?i)Hello").asPredicate()).count();
您可能在 if 语句中有一个 integer 计数器。 它会在用 ++ 打印该行之前/之后迭代。
好吧,如果你已经让你的循环打印出包含单词“hello”的每一行,并且你需要计算你 go 通过的这些行的数量,你为什么不......计算它:)
换句话说,尝试初始化一个 integer 计数器并为包含单词“hello”的每一行递增该计数器。
希望这可以帮助。 不发布任何代码,因为这似乎是我不想从你那里拿走的好习惯!
有时先用伪代码看问题更容易,这样可以避开语言的细节,更专注于解决方案:
function countLinesWith(targetWord, textFile)
lineCount <- 0
repeat
thisLine <- readNextLine(textFile)
if (thisLine.contains(targetWord) {
lineCount <- lineCount + 1
}
until(textFile.EoF)
return lineCount
end function
然后将伪代码翻译成您选择的语言。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.