ios CSV解析- Swift 4

huwehgph  于 2023-04-08  发布在  iOS
关注(0)|答案(3)|浏览(144)

我正在尝试解析CSV,但遇到了一些问题。下面是我用于解析CSV的代码:

let fileURL = Bundle.main.url(forResource: "test_application_data - Sheet 1", withExtension: "csv")
let content = try String(contentsOf: fileURL!, encoding: String.Encoding.utf8)
let parsedCSV: [[String]] = content.components(separatedBy: "\n").map{ $0.components(separatedBy: ",")}

这是我正在解析的CSV中的数据:

Item 9,Description 9,image url 
"Item 10 Extra line 1 Extra line 2 Extra line 3",Description 10,image url

因此,通过使用上面的代码,我得到了第一行的正确响应,即Item 9,但我得到了Item 10的错误响应
如何正确地解析这两行?

pobjuy32

pobjuy321#

CSV的RFC:Common Format and MIME Type for Comma-Separated Values (CSV) Files(RFC-4180)
并非所有CSV数据或CSV处理器都符合本RFC的所有描述,但通常,双引号内的字段可以包含:

  • 新行
  • 逗号
  • 转义双引号(""表示单个双引号)

这段代码比RFC-4180稍微简化了一点,但可以处理以上所有三种情况:

UPDATE这段旧代码不能很好地处理CRLF。(这是RFC-4180中有效的换行符。)我在底部添加了一段新代码,请检查。感谢Jay。

import Foundation

let csvText = """
Item 9,Description 9,image url
"Item 10
Extra line 1
Extra line 2
Extra line 3",Description 10,image url
"Item 11
Csv item can contain ""double quote"" and comma(,)", Description 11 ,image url
"""

let pattern = "[ \r\t]*(?:\"((?:[^\"]|\"\")*)\"|([^,\"\\n]*))[ \t]*([,\\n]|$)"
let regex = try! NSRegularExpression(pattern: pattern)

var result: [[String]] = []
var record: [String] = []
let offset: Int = 0
regex.enumerateMatches(in: csvText, options: .anchored, range: NSRange(0..<csvText.utf16.count)) {match, flags, stop in
    guard let match = match else {fatalError()}
    if match.range(at: 1).location != NSNotFound {
        let field = csvText[Range(match.range(at: 1), in: csvText)!].replacingOccurrences(of: "\"\"", with: "\"")
        record.append(field)
    } else if match.range(at: 2).location != NSNotFound {
        let field = csvText[Range(match.range(at: 2), in: csvText)!].trimmingCharacters(in: .whitespaces)
        record.append(field)
    }
    let separator = csvText[Range(match.range(at: 3), in: csvText)!]
    switch separator {
    case "\n": //newline
        result.append(record)
        record = []
    case "": //end of text
        //Ignoring empty last line...
        if record.count > 1 || (record.count == 1 && !record[0].isEmpty) {
            result.append(record)
        }
        stop.pointee = true
    default: //comma
        break
    }
}
print(result)

(预期在Playground进行测试。)

新编码,CRLF就绪。

import Foundation

let csvText =  "Field0,Field1\r\n"

let pattern = "[ \t]*(?:\"((?:[^\"]|\"\")*)\"|([^,\"\r\\n]*))[ \t]*(,|\r\\n?|\\n|$)"
let regex = try! NSRegularExpression(pattern: pattern)

var result: [[String]] = []
var record: [String] = []
let offset: Int = 0
regex.enumerateMatches(in: csvText, options: .anchored, range: NSRange(0..<csvText.utf16.count)) {match, flags, stop in
    guard let match = match else {fatalError()}
    if let quotedRange = Range(match.range(at: 1), in: csvText) {
        let field = csvText[quotedRange].replacingOccurrences(of: "\"\"", with: "\"")
        record.append(field)
    } else if let range = Range(match.range(at: 2), in: csvText) {
        let field = csvText[range].trimmingCharacters(in: .whitespaces)
        record.append(field)
    }
    let separator = csvText[Range(match.range(at: 3), in: csvText)!]
    switch separator {
    case "": //end of text
        //Ignoring empty last line...
        if record.count > 1 || (record.count == 1 && !record[0].isEmpty) {
            result.append(record)
        }
        stop.pointee = true
    case ",": //comma
        break
    default: //newline
        result.append(record)
        record = []
    }
}
print(result) //->[["Field0", "Field1"]]
yfwxisqw

yfwxisqw2#

问题出在这行代码上:

content.components(separatedBy: "\n")

它根据换行符将你的csv文件分成行。在你的"Item 10 Extra line 1 Extra line 2 Extra line 3" String中有换行符,所以每一个额外的行都被视为不同的行,所以最后你得到了错误的结果。
我建议在你的多行文本列中转义换行符或者完全去掉它们。你也可以修改输入文件,这样换行符就不是每行末尾的\n,而是自定义的(一个不会出现在csv文件其他地方的字符串)。

svdrlsy4

svdrlsy43#

我认为最好的选择是使用TabularData https://developer.apple.com/documentation/tabulardata

if let url = Bundle.main.url(forResource: "Table", withExtension: "csv"),
   let data = try? DataFrame.init(contentsOfCSVFile: url) {
    print(data.rows)
    
    let array: [Model] = data.rows.map { row in
        let value1 = row["ColumnKey1", String.self]
        let value2 = row["ColumnKey2", String.self]
        return Model(value1: value1, value2: value2)
    }
    print(array)
} else {
    print("Error")
}

相关问题