如何从Swift中的txt文件创建字典数组?

时间:2015-03-02 04:14:42

标签: arrays parsing swift dictionary

这是txt文件的示例。

  

ROUTE_ID,agency_id,route_short_name,route_long_name,route_desc,route_type,route_url,route_color,route_text_color

     

53739,,11,11TH AVENUE ,, 3,,3333CC,FFFFFF

     

53740 ,, 17,1700 SOUTH ,, 3,,3333CC,FFFFFF   53741,2,200 SOUTH ,, 3,,3333CC,FFFFFF

第一行显示元素的名称,每个组件用逗号分隔。

我想创建一个如下所示的字典数组:

[[“route_id”:“53739”,“agency_id”:“”,“route_short_name”:“17”......]

[“route_id”:“53740”,“agency_id”:“”......]]

我猜你有这个主意。

2 个答案:

答案 0 :(得分:1)

来源:http://pjeremymalouf.com/scan-a-csv-into-swift/

import Foundation

class CSVScanner {

    class func arrayOfDictionaryFromFile(#columnNames:Array<String>, fromFile theFileName:String, withFunction theFunction:(Dictionary<String, String>)->()) {

        if let strBundle = NSBundle.mainBundle().pathForResource(theFileName, ofType: "csv") {

            var encodingError:NSError? = nil

            if let fileObject = NSString(contentsOfFile: strBundle, encoding: NSUTF8StringEncoding, error: &encodingError){

                var fileObjectCleaned = fileObject.stringByReplacingOccurrencesOfString("\r", withString: "\n")

                fileObjectCleaned = fileObjectCleaned.stringByReplacingOccurrencesOfString("\n\n", withString: "\n")

                let objectArray = fileObjectCleaned.componentsSeparatedByString("\n")

                for anObjectRow in objectArray {

                    let objectColumns = anObjectRow.componentsSeparatedByString(",")

                    var aDictionaryEntry = Dictionary<String, String>()

                    var columnIndex = 0

                    for anObjectColumn in objectColumns {

                        aDictionaryEntry[columnNames[columnIndex]] = anObjectColumn.stringByReplacingOccurrencesOfString("\"", withString: "", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)

                        columnIndex++
                    }

                    if (aDictionaryEntry.count > 1) {
                        theFunction(aDictionaryEntry)
                    }
                }
            }
        }
    }
}

如何使用它:

var myCSVContents = Array<Dictionary<String, String>>()

CSVScanner.runFunctionOnRowsFromFile(["title", "body", "category"], withFileName: "fileName.csv", withFunction: {

    (aRow:Dictionary<String, String>) in

    myCSVContents.append(aRow)

})

确保将文件另存为.csv或调整代码以查找.txt

答案 1 :(得分:0)

我建议您使用JSON格式制作文本文件并解析它。我认为这将是你更容易的方式。