如何解析.txt文件并从swift 3中获取数据

时间:2017-08-01 09:58:15

标签: swift3 text-parsing

我有一个文本文件,我想从中解析数据,我想从该文本文件中获取一些数据,城市名称,最大温度,年份, 这是文本文件enter link description here的链接 我想从这个网址获得uk,max temp,year和temp。我如何解析它并从此文本文件中获取数据。例如,UK,Max temp,1910,JAN,5.4。这可以解析并从此文本文件中获取数据吗? 任何建议将不胜感激。

1 个答案:

答案 0 :(得分:1)

在Swift 3.0中,您可以像这样解析txt文件:

let file = "file.txt" //this is the file. we will write to and read from it

let text = "some text" //just a text

if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {

    let path = dir.appendingPathComponent(file)

    //writing
    do {
        try text.write(to: path, atomically: false, encoding: String.Encoding.utf8)
    }
    catch {/* error handling here */}

    //reading
    do {
        let text2 = try String(contentsOf: path, encoding: String.Encoding.utf8)
    }
    catch {/* error handling here */}
}

注意:如果您想阅读一些静态数据,我的建议将始终是本地保存的 JSON 文件。

<强> 编辑:

还有一种方法,也许更简单的方法:

let path = NSBundle.mainBundle().pathForResource("FileName", ofType: "txt")
var text = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)!
println(text)

编辑:

This is API example for your need in JSON