gpt4 book ai didi

csv - Golang : While processing CSV, 重新格式化单行?

转载 作者:IT王子 更新时间:2023-10-29 02:21:58 26 4
gpt4 key购买 nike

我的 golang CSV 处理例程几乎完全复制自 Package CSV示例:

func processCSV(path string){

file:= utils.OpenFile(path)
reader:= csv.NewReader(file)
reader.LazyQuotes = true

cs:= []*Collision{} //defined elsewhere

for {

line, err := reader.Read()

//Kill processing if we're at EOF
if err == io.EOF {
break
}

c := get(line) //defined elsewhere
cs= append(cs, c)
}

//Do other stuff...
}

代码在遇到格式错误(?)的 CSV 行之前运行良好,通常看起来像这样:

item1,item2,"item3,"有奇怪的引号"","item4",item5

csvReader.LazyQuotes = true 选项似乎没有提供足够的容忍度来读取我需要的这一行。

我的问题是:我可以向 csv 阅读器索取原始行,以便我可以“按摩”它以提取我需要的内容吗?我正在处理的文件比较大 (~150mb),我不确定是否要重做它们,尤其是每个文件只有几行存在此类问题。

感谢任何提示!

最佳答案

据我所知,encoding/csv 不提供任何此类功能,因此您可以寻找一些具有此功能的第 3 方 csv 包,或者您可以自己实现解决方案。

如果你想走 DIY 路线,我可以给你一个提示,你是否应该实现一个好的提示取决于你。

您可以实现一个 io.Reader 来包装您的文件并跟踪读取的最后一行,然后每次您因为格式错误的 csv 遇到错误时,您可以使用您的阅读器重新读取该行,massage它,将其添加到结果中,然后继续循环,就好像什么都没发生一样。

这是您的 processCSV 将如何更改的示例:

func processCSV(path string){

file := utils.OpenFile(path)
myreader := NewMyReader(file)
reader := csv.NewReader(myreader)
reader.LazyQuotes = true

cs:= []*Collision{} //defined elsewhere

for {

line, err := reader.Read()

//Kill processing if we're at EOF
if err == io.EOF {
break
}

// malformed csv
if err != nil {
// Just reread the last line and on the next iteration of
// the loop myreader.Read should continue returning bytes
// that come after this malformed line to the csv.Reader.
l, err := myreader.CurrentLine()
if err != nil {
panic(err)
}

// massage the malformed csv line
line = fixcsv(l)
}

c := get(line) //defined elsewhere
cs= append(cs, c)
}

//Do other stuff...
}

关于csv - Golang : While processing CSV, 重新格式化单行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44009431/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com