英文:
Fetching CSV data using Golang
问题
如下所示,我已经读取了CSV文件并使用索引获取了数据。然后,我将标题名称与其相应的索引对齐。
现在,我该如何使用标题名称而不是索引从CSV文件中获取特定数据?我对Golang和编程都很陌生。
func main() {
file, ferr := os.Open("company1.csv")
if ferr != nil {
panic(ferr)
}
reader := csv.NewReader(file)
reader.Comma = '|'
reader.Comma = ','
records, _ := reader.ReadAll()
fmt.Println(records) // 打印所有记录
fmt.Println("\n", records[1][0]) // 打印第一条记录
fmt.Println("\n", records[0]) // 头部
// 打印标题与索引
index := 0
for _, x := range records[0] {
fmt.Println("\n", x, "-", index)
index++
}
}
请注意,这只是读取CSV文件并打印数据的示例代码,并没有使用标题名称来获取特定数据。如果你想使用标题名称来获取数据,你需要编写逻辑来匹配标题名称并提取相应的数据。
英文:
As you can see below I have read the CSV file and also fetched data using the index. After that, I aligned the header name with its respective index.
Now, how can I fetch particular data from the CSV file using the header name and not the index? I'm new to Golang and programming.
func main() {
file, ferr := os.Open("company1.csv")
if ferr != nil {
panic(ferr)
}
reader := csv.NewReader(file)
reader.Comma = '|'
reader.Comma = ','
records, _ := reader.ReadAll()
fmt.Println(records) // prints all the records
fmt.Println("\n",records[1][0]) //to print the first record
fmt.Println("\n",records[0]) // header
//to print the index along the header
index := 0
for _, x := range records[0] {
fmt.Println("\n",x ,"-",index)
index++
}
答案1
得分: 4
创建一个从标题名称到列索引的映射。在索引记录时使用该映射:
fields := make(map[string]int)
for i, name := range records[0] {
fields[name] = i
}
for _, record := range records[1:] {
x := record[fields["name"]]
fmt.Println(x)
}
上述代码没有处理文件中缺少预期列的情况。在循环遍历数据记录之前,添加以下检查:
for _, name := range []string{"name", "column2"} {
if _, ok := fields[name]; !ok {
log.Fatal("field missing:", name)
}
}
英文:
Create a map from header name to column index. Use that map when indexing a record:
fields := make(map[string]int)
for i, name := range records[0] {
fields[name] = i
}
for _, record = range records[1:] {
x = record[fields["name"]]
fmt.Println(x)
}
The above code does not handle the case where an expected column is missing from the file. Add this check before looping through the data records:
for _, name := range []string{"name", "column2"} {
if _, ok := fields[name]; !ok {
log.Fatal("field missing", name)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论