need help to read file with specific formatted contents

隐身守侯 提交于 2019-12-12 09:58:48

问题


i'm using F#. I want to solve some problem that require me to read the input from a file, i don't know what to do. The first line in the file consist of three numbers, the first two numbers is the x and y for an map for the next line. The example file:

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

the meaning of 5 5 10 is the next line have 5x5 map and 10 is just some numbers that i need to solve the problem, the next until the end of the line is contents of the map that i have to solve using the 10 and i want to save this map numbers in 2 dimensional array. Someone can help me to write a code to save the all the numbers from the file so i can process it? * Sorry my english is bad, hope my question can be understood :)

The answer for my own question : Thanks for the answer from Daniel and Ankur. For my own purpose i mix code from both of you:

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

Many Thanks :D


回答1:


Here's some quick and dirty code. It returns a tuple of the last number in the header (10 in this case) and a two-dimensional array of the values.

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:


In case the file is this much only (no further data to process) and always in correct format (no need to handle missing data etc) then it would be as simple as:

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
    |]


来源:https://stackoverflow.com/questions/7583636/need-help-to-read-file-with-specific-formatted-contents

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!