gpt4 book ai didi

csv - 解析csv文件时出现奇怪的输出

转载 作者:IT王子 更新时间:2023-10-29 01:57:39 42 4
gpt4 key购买 nike

我正在使用 golang 从 google api 解析一个 csv 文件,该文件以 utf-16 编码,下面的代码尝试读取一条记录(跳过标题)并打印记录,但它给我这样的输出很奇怪:

, v=/09/20 00:35:42 k=Smartfren Andromax AD681H

我猜想可能和utf-16编码有关,但不知 Prop 体细节,代码如下: 包主

import (
"encoding/csv"
"io"
"log"
"net/http"
"strings"
)

var url = "http://storage.googleapis.com/play_public/supported_devices.csv"

func main() {

resp, err := http.Get(url)
if err != nil {
return
}
defer resp.Body.Close()

r := csv.NewReader(resp.Body)
r.LazyQuotes = true
r.FieldsPerRecord = -1
// skip header
r.Read()

m := make(map[string]string)
for {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
log.Println(err)
continue
}
if len(record) >= 4 {
m[strings.TrimSpace(record[3])] = strings.TrimSpace(record[1])
for k, v := range m {
log.Printf("k=%s, v=%s\n", k, v)
}
break
}
}
}

最佳答案

如您所料,输入数据必须从 UTF-16 编码字符流转换为 UTF-8 编码字符流。您可以使用 Go 子存储库包来做到这一点 golang.org/x/text/encoding/unicode :

package main

import (
"encoding/csv"
"io"
"log"
"net/http"
"strings"

"golang.org/x/text/encoding/unicode"
)

var url = "http://storage.googleapis.com/play_public/supported_devices.csv"

func main() {

resp, err := http.Get(url)
if err != nil {
return
}
defer resp.Body.Close()

dec := unicode.UTF16(unicode.LittleEndian, unicode.UseBOM).NewDecoder()
reader := dec.Reader(resp.Body)

r := csv.NewReader(reader)
r.LazyQuotes = true
r.FieldsPerRecord = -1
// skip header
r.Read()

m := make(map[string]string)
for {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
log.Println(err)
continue
}
if len(record) >= 4 {
m[strings.TrimSpace(record[3])] = strings.TrimSpace(record[1])
for k, v := range m {
log.Printf("k=%s, v=%s\n", k, v)
}
break
}
}
}

关于csv - 解析csv文件时出现奇怪的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46305956/

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