1 回答

TA貢獻1784條經驗 獲得超7個贊
CSV沒有“可變長度數組”的概念,它只是一個逗號分隔的值列表。該格式在RFC 4180中進行了描述,這正是該encoding/csv包所實現的。
您只能從 CSV 行中獲取字符串切片。如何解釋這些值取決于您。如果要進一步拆分數據,則必須對數據進行后期處理。
您所擁有的可能會簡單地使用regexp包裹進行處理,例如
var r = regexp.MustCompile(`'[^']*'`)
func split(s string) []string {
parts := r.FindAllString(s, -1)
for i, part := range parts {
parts[i] = part[1 : len(part)-1]
}
return parts
}
測試它:
s := `['one', 'two', 'three']`
fmt.Printf("%q\n", split(s))
s = `[]`
fmt.Printf("%q\n", split(s))
s = `['o,ne', 't,w,o', 't,,hree']`
fmt.Printf("%q\n", split(s))
輸出(在Go Playground上試試):
["one" "two" "three"]
[]
["o,ne" "t,w,o" "t,,hree"]
使用此split()函數,處理可能如下所示:
for _, line := range lines {
data := CsvLine{
Id: line[0],
Array1: split(line[1]),
Array2: split(line[2]),
}
fmt.Printf("%+v\n", data)
}
這個輸出(在Go Playground上試試):
{Id:594385903dss Array1:[fhjdsk dfjdskl fkdsjgooiertio] Array2:[jflkdsjfl fkjdlsfjdslkfjldks]}
{Id:87764385903dss Array1:[cxxc wqeewr opi iy qw] Array2:[cvbvc gf mnb ewr]}
- 1 回答
- 0 關注
- 167 瀏覽
添加回答
舉報