【问题标题】:need help to read file with specific formatted contents需要帮助来读取具有特定格式内容的文件
【发布时间】:2011-09-29 01:31:05
【问题描述】:

我正在使用 F#。我想解决一些需要我从文件中读取输入的问题,我不知道该怎么做。文件中的第一行由三个数字组成,前两个数字是下一行的地图的 x 和 y。示例文件:

5 5 10
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

5 5 10 的含义是下一行有 5x5 地图,10 只是我需要解决问题的一些数字,下一行直到行尾是我必须使用解决的地图内容10,我想将此地图编号保存在二维数组中。有人可以帮我写一个代码来保存文件中的所有数字,这样我就可以处理它了吗? * 抱歉我的英文不好,希望我的问题能被理解:)

我自己的问题的答案: 感谢 Daniel 和 Ankur 的回答。为了我自己的目的,我混合了你们俩的代码:

let readMap2 (path:string) =
    let lines = File.ReadAllLines path
    let [|x; y; n|] = lines.[0].Split() |> Array.map int
    let data = 
        [| 
            for l in (lines |> Array.toSeq |> Seq.skip 1) do
                yield l.Split() |> Array.map int
        |]
    x,y,n,data

非常感谢:D

【问题讨论】:

    标签: f#


    【解决方案1】:

    这里有一些快速而肮脏的代码。它返回标题中最后一个数字的元组(在本例中为 10)和值的二维数组。

    open System.IO
    
    let readMap (path:string) =
      use reader = new StreamReader(path)
      match reader.ReadLine() with
      | null -> failwith "empty file"
      | line -> 
        match line.Split() with
        | [|_; _; _|] as hdr -> 
          let [|x; y; n|] = hdr |> Array.map int
          let vals = Array2D.zeroCreate y x
          for i in 0..(y-1) do
            match reader.ReadLine() with
            | null -> failwith "unexpected end of file"
            | line -> 
              let arr = line.Split() |> Array.map int
              if arr.Length <> x then failwith "wrong number of fields"
              else for j in 0..(x-1) do vals.[i, j] <- arr.[j]
          n, vals
        | _ -> failwith "bad header"
    

    【讨论】:

    • 啊,是的,谢谢,对不起,我忘记了一些事情,我想将地图内容保存在二维数组中,你能帮帮我吗
    • 我使用了锯齿状数组,因为它们的性能更好,但我将其更新为使用二维数组。
    【解决方案2】:

    如果文件只有这么多(无需处理更多数据)并且格式始终正确(无需处理丢失的数据等),那么它会很简单:

    let readMap (path:string) =
        let lines = File.ReadAllLines path
        let [|_; _; n|] = lines.[0].Split() |> Array.map int
        [| 
            for l in (lines |> Array.toSeq |> Seq.skip 1) do
                yield l.Split() |> Array.map int
        |]
    

    【讨论】:

      猜你喜欢
      • 2014-02-06
      • 1970-01-01
      • 1970-01-01
      • 2013-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-28
      相关资源
      最近更新 更多