【问题标题】:parsing values from text file in java从java中的文本文件解析值
【发布时间】:2014-05-30 18:15:06
【问题描述】:

我有一些文本文件需要从中提取数据。该文件本身包含大约一百行,对我来说有趣的部分是:

AA====== test==== ====================================================/
AA    normal         low          max          max2         max3      /
AD     .45000E+01   .22490E+01   .77550E+01   .90000E+01   .47330E+00 /

假设我需要提取“正常”、“低”和“最大”下的双精度值。除了对文本文件进行正则表达式之外,还有其他有效且不太容易出错的解决方案吗?

【问题讨论】:

  • split() 有什么问题?
  • 我需要知道上下文,文件中还有很多其他行
  • 我会研究语法:)

标签: java text text-parsing


【解决方案1】:

如果您真的想避免使用正则表达式,并假设您将始终使用相同的基本格式,您可以执行以下操作:

HashMap<String, Double> map = new HashMap<>();
Scanner scan = new Scanner(filePath); //or your preferred input mechanism
assert (scan.nextLine().startsWith("AA====:); //remove the top line, ensure it is the top line

while (scan.hasNextLine()){
   String[] headings = scan.nextLine().split("\\s+"); //("\t") can be used if you're sure the delimiters will always be tabs
   String[] vals = scan.nextLine().split("\\s+");
   assert headings[0].equals("AA"); //ensure  
   assert vals[0].equals("AD"); 
   for (int i = 1; i< headings.length; i++){ //start with 1
       map.put(headings[i], Double.parseDouble(vals[i]);
   }
}
   //to make sure a certain value is contained in the map: 
   assert map.containsKey("normal");
   //use it:
   double normalValue = map.get("normal"); 
}

代码未经测试,因为我目前无法访问 IDE。另外,我显然不知道什么是可变的,什么将在这里保持不变(阅读:“AD”、“AA”等),但希望您能掌握要点并可以根据需要进行修改。

【讨论】:

  • 如果您不确定使用的是什么空白字符,最好使用scan.nextLine().split("\\s+")
  • 相比nextLine().split(),您可能会发现使用Scanner.findInLine()Scanner.nextLine() 更简洁
  • @KelvinNg 我同意,但我不希望解决方案依赖于Scanner 方法。 .nextLine().split() 可以轻松适应任何输入机制(例如,BufferedReader 可以通过将其更改为 readLine().split() 来使用),而 Scanner.findInLine() 则相当独特。
【解决方案2】:

如果每一行总是有这种精确的形式,你可以使用String.split()

String line; // Fill with one line from the file
String[] cols = line.split(".")

String normal = "."+cols[0]
String low = "."+cols[1]
String max = "."+cols[2]

【讨论】:

    【解决方案3】:

    如果您知道每个值将从哪个索引开始,您可以只做该行的子字符串。 (split 方法在技术上是一个正则表达式)。

     String normal = line.substring(x, y).trim();
     String low = line.substring(z, w).trim();
    

    等等

    【讨论】:

      猜你喜欢
      • 2011-09-29
      • 1970-01-01
      • 1970-01-01
      • 2017-05-08
      • 1970-01-01
      • 2023-03-31
      • 2012-02-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多