需要帮助来读取具有特定格式内容的文件 [英] need help to read file with specific formatted contents

查看:70
本文介绍了需要帮助来读取具有特定格式内容的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用F#.我想解决一些问题,我需要从文件中读取输入,但我不知道该怎么办.文件中的第一行包含三个数字,前两个数字是下一行映射的x和y.示例文件:

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

5 5 10的意思是下一行具有5x5映射,而10只是一些我需要解决的数字,下一行直到行尾是我必须使用来解决的地图内容10,我想将此地图编号保存为二维数组.有人可以帮助我编写代码以保存文件中的所有数字,以便我可以对其进行处理? *对不起,我的英语不好,希望我的问题能被理解:)

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 :)

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

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

非常感谢:D

推荐答案

下面是一些快速而肮脏的代码.它返回标头中最后一个数字的元组(在这种情况下为10)和值的二维数组.

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"

这篇关于需要帮助来读取具有特定格式内容的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆