我使用Swiftcsv库来解析CSV文件。 如何忽略DoubleQuotes中字符串的逗号分隔符,例如“Abcd,去了Apple”? 这里解析器将 Abcd 作为一个值,作为另一个值转到Apple 。
代码:
func parseRows(fromLines lines: [String]) -> [Dictionary<String, String>] {
var rows: [Dictionary<String, String>] = []
for (lineNumber, line) in enumerate(lines) {
if lineNumber == 0 {
continue
}
var row = Dictionary<String, String>()
let values = line.componentsSeparatedByCharactersInSet(self.delimiter)
for (index, header) in enumerate(self.headers) {
let value = values[index]
row[header] = value
}
rows.append(row)
}
return rows
}
如何更改 line.componentsSeparatedByCharactersInSet(self.delimiter)以忽略Doublequotes中的逗号?
答案 0 :(得分:3)
使用此代替https://github.com/Daniel1of1/CSwiftV
有同样的问题。我花了一个小时左右的时间来弄清楚问题是SwiftCSV没有,呃,工作。
CSV文件中的文字在引号内,因此CSV中的逗号和换行符不会搞砸解析器。我查看了SwiftCSV源代码并且没有支持 - 这意味着任何逗号或换行符都会破坏解析。
您可以修补SwiftCSV,或者只使用上面链接的 CSwiftV 。
答案 1 :(得分:1)
我不知道您是否仍在寻找解决方案,但我想出了一个快速的方法来解决这个问题,因为这是我遇到的问题。
代码不是完全证明,因为我只是将它用于辅助项目,所以如果你想处理更多的情况,你可能需要做一些改变。
func parseRows(fromLines lines: [String]) -> [Dictionary<String, String>] {
var rows: [Dictionary<String, String>] = []
for (lineNumber, line) in enumerate(lines) {
if lineNumber == 0 {
continue
}
var row = Dictionary<String, String>()
// escape commas in the string when it is surrounded by quotes
let convertedLine = NSString(string: line) // have to convert string to NSString because string does not have all NSString API
var escapedLine = line
var searchRange = NSMakeRange(1,convertedLine.length)
var foundRange:NSRange
if NSString(string: line).containsString("\"")
{
while (searchRange.location < convertedLine.length) {
searchRange.length = convertedLine.length-searchRange.location
foundRange = convertedLine.rangeOfString("\"", options: nil, range: searchRange)
if (foundRange.location != NSNotFound) {
// found a quotation mark
searchRange.location = foundRange.location+foundRange.length
let movieTitle = convertedLine.substringToIndex(foundRange.location)
escapedLine = convertedLine.stringByReplacingOccurrencesOfString(",", withString: "&c", options: nil, range: NSMakeRange(0,foundRange.location))
} else {
// no more substring to find
break
}
}
}
var values = escapedLine.componentsSeparatedByCharactersInSet(self.delimiter)
for (index, header) in enumerate(self.headers) {
var value = values[index]
//reinsert commas if they were escaped and get rid of quotation marks
value = value.stringByReplacingOccurrencesOfString("\"", withString: "")
value = value.stringByReplacingOccurrencesOfString("&c", withString: ",")
row[header] = value
}
rows.append(row)
}
return rows
}