数组 – 将.csv数据导入数组

数组 – 将.csv数据导入数组,第1张

概述我在过去几年使用Objective-C. 现在我正在尝试 Xcode 6 beta 4与迅速. 我想导入一个.csv表单我的webserver到一个数组.我在Objective-C中的旧代码是: NSString *stringURL = @"https:// [URL] /versionen/versionen.csv";NSURL *url = [NSURL URLWithString:s 我在过去几年使用Objective-C.
现在我正在尝试 Xcode 6 beta 4与迅速.

我想导入一个.csv表单我的webserver到一个数组.我在Objective-C中的旧代码是:

Nsstring *stringURL = @"https:// [URL] /versionen/versionen.csv";NSURL  *url = [NSURL URLWithString:stringURL];NSData *urlData = [NSData dataWithContentsOfURL:url];if ( urlData ){    Nsstring *csvResponseString = [[Nsstring alloc] initWithData:urlData   enCoding:NSUTF8StringEnCoding];    NSArray         *MZVersionDatenZeilen = [csvResponseString componentsSeparatedByString:@"\n"];    NSEnumerator    *MZVersionEnumerator = [MZVersionDatenZeilen objectEnumerator];    NSMutableArray  *MZVersionDatenArray = [NSMutableArray arrayWithCapacity:[MZVersionDatenZeilen count]];    Nsstring        *MZVersionZeile;    while (MZVersionZeile = [MZVersionEnumerator nextObject])    {        [MZVersionDatenArray addobject:[MZVersionZeile componentsSeparatedByString:@";"]];    }}

我怎么可以在Swift这样做?
有最佳做法 – 推荐吗?

有多个swift库可用:

CSVImporter,它是一个适用于处理大型csv文件的异步解析器.

let path = "path/to/your/CSV/file"let importer = CSVimporter<[String]>(path: path)importer.startimportingRecords { 
let csvURL = NSURL(string: "users.csv")!var error: NSErrorPointer = nillet csv = CSV(contentsOfURL: csvURL,error: error)// Rowslet rows = csv.rowslet headers = csv.headers  //=> ["ID","name","age"]let alice = csv.rows[0]    //=> ["ID": "1","name": "Alice","age": "18"]let bob = csv.rows[1]      //=> ["ID": "2","name": "Bob","age": "19"]// Columnslet columns = csv.columnslet names = csv.columns["name"]  //=> ["Alice","Bob","CharlIE"]let ages = csv.columns["age"]    //=> ["18","19","20"]
}.onFinish { importedRecords in for record in importedRecords { // record is of type [String] and contains all data in a line }}

SwiftCSV,它是一个用于OSX和iOS的简单CSV解析库.

let inputString = "Year,Make,Model,Description,Price\r\n1997,Ford,E350,descrition,3000.00\r\n1999,Chevy,Venture,another description,4900.00\r\n"let csv = CSwiftV(String: inputString)let headers = csv.headers // ["Year","Make","Model","Description","Price"]let rows = csv.rows // [//  ["1997","Ford","E350","descrition","3000.00"],//  ["1999","Chevy","Venture","another description","4900.00"]// ]

和CSwiftV,它是符合rfc4180规范的csv解析器,但根据作者,它全部在内存中,因此不适合大文件.

总结

以上是内存溢出为你收集整理的数组 – 将.csv数据导入数组全部内容,希望文章能够帮你解决数组 – 将.csv数据导入数组所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1028241.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存