需要帮助读取具有特定格式内容的文件
我正在使用 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 和我想将此地图编号保存在二维数组中。有人可以帮我编写一个代码来保存文件中的所有数字,以便我可以处理它吗? * 抱歉我的英语不好,希望我的问题能被理解:)
我自己问题的答案: 感谢丹尼尔和安库尔的回答。为了我自己的目的,我混合了你们俩的代码:
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一些快速而肮脏的代码。它返回标头中最后一个数字的元组(在本例中为 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.
如果文件只有这么多(没有更多的数据要处理)并且始终采用正确的格式(不需要处理丢失的数据等),那么它会很简单:
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: