首頁 > 後端開發 > Golang > 主體

如何使用 Go 的 `encoding/csv` 套件處理 CSV 編碼中帶引號的字串?

Mary-Kate Olsen
發布: 2024-10-27 09:13:30
原創
963 人瀏覽過

How do you handle quoted strings in CSV encoding with Go's `encoding/csv` package?

Go中的CSV編碼:處理帶引號的字串

在Go的encoding/csv包中,處理引號的字符串有時會導致意想不到的結果。在編寫 CSV 記錄時,了解編碼特殊字元(例如雙引號)的標準要求至關重要。

根據 CSV 規範,欄位中的雙引號字元必須使用第二個雙引號字元進行轉義。出於解析原因,此轉義序列是必需的。

範例:

<code class="go">import "encoding/csv"

record := []string{
    "Unquoted string",
    "Cr@zy text with , and \ and \" etc",
}

writer := csv.NewWriter(writer)
writer.Write(record)</code>
登入後複製

上面的程式碼將寫入雙引號轉義的字串:

<code class="csv">Unquoted string
"Cr@zy text with , and \ and \" etc"</code>
登入後複製

避免額外引號:

要避免在讀取CSV 檔案時插入額外引號,應採取以下步驟:

  • 寫入時帶引號的字串,使用fmt.Sprintf("%q", string) 正確轉義雙引號。
  • 讀取帶引號的字串時,CSV 讀取器會自動取消雙引號轉義,確保取得原始字串.

程式碼範例:

<code class="go">func writeCSV() {
    writer := csv.NewWriter(writer)
    s := "Cr@zy text with , and \ and \" etc"

    record := []string{
        "Unquoted string",
        "Quoted string",
        fmt.Sprintf("%q", s),
    }

    writer.Write(record)
}

func readCSV() {
    reader := csv.NewReader(reader)
    records, err := reader.ReadAll()

    for _, record := range records {
        // Printed records automatically have double quotes unescaped by the CSV reader.
        fmt.Println(record)
    }
}</code>
登入後複製

輸出:

[Unquoted string Cr@zy text with , and \ and " etc]
[Quoted string Cr@zy text with , and \ and " etc]
登入後複製

以上是如何使用 Go 的 `encoding/csv` 套件處理 CSV 編碼中帶引號的字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!