簡體   English   中英

從較長的文本/文件中提取出現在特定單詞之后的數字

[英]Extracting a number that occurs after a specific word from a longer text/file

我有5631行的文本文件。 我想提取並存儲出現在單詞字節后面的數字

該文件中間的示例行形式如下:

debug3: In write loop, ack for 1606 32768 bytes at 52527104

在這里,我想要值52527104 此值每增加一行,我的目標是根據每行值計算完成百分比。 通過使用公式((obtained*100)/total)

謝謝。

您可以簡單地將讀取行按字節分割並使用索引1處的值。 我使用了Long解析器,可以根據需要使用Integer 該代碼將忽略不包含提供的模式的行。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class BytesAt {
  public static void main(String[] args) throws FileNotFoundException {
    Scanner read = new Scanner(new File("input.txt"));
    while (read.hasNextLine()) {
      String line = read.nextLine();
      String parts[] = line.split("bytes at");
      if(parts.length > 1) {
        System.out.println("Value as String: " + parts[1].trim());
        System.out.println("Value as Long: " + Long.parseLong(parts[1].trim()));
      }
    }
  }
}

怎么樣:

long totalBytes = //Whatever source.
long currValue = 0;
for (String line: lines) {
  if (line.contains("bytes at")) {
    long currValue = Long.parseLong(line.split("bytes at\\s")[1]);
  }
  System.out.println("Completed % = "+(float)(currValue/totalBytes*100);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM