08.8 读取CSV文件

CSV文件是纯文本文件。在本节中,你将学习如何读取包含平面点的文本文件,这意味着每一行将包含一对坐标。此外,你还将使用一个名为Glot的外部Go库,它将帮助你创建从CSV文件中读取的点的图表。注意,Glot使用Gnuplot,这意味着你需要在Unix机器上安装Gnuplot才能使用Glot

本章的程序是CSVplot.go,分为五部分。第一部分代码如下:

package main

import (
    "encoding/csv"
    "fmt"
    "github.com/Arafatk/glot"
    "os"
    "strconv"
)

CSVplot.go第二部分代码如下:

func main() {
    if len(os.Args) != 2 {
        fmt.Println("Need a data file!")
        return
    }

    file := os.Args[1]
    _, err := os.Stat(file)
    if err != nil {
        fmt.Println("Cannot stat", file)
        return
    }

在本部分中,你将看到一种使用强大的os.Stat()函数检查文件是否已经存在的技术。

CSVplot.go第三部分代码如下:

    f, err := os.Open(file)
    if err != nil {
        fmt.Println("Cannot open", file)
        fmt.Println(err)
        return
    }
    defer f.Close()

    reader := csv.NewReader(f)
    reader.FieldsPerRecord = -1
    allRecords, err := reader.ReadAll()
    if err != nil {
        fmt.Println(err)
        return
    }

CSVplot.go第四部分代码如下:

    xP := []float64{}
    yP := []float64{}

    for _, rec := range allRecords {
        x, _ := strconv.ParseFloat(rec[0], 64)
        y, _ := strconv.ParseFloat(rec[1], 64)
        xP = append(xP, x)
        yP = append(yP, y)
    }

    points := [][]float64{}
    points = append(points, xP)
    points = append(points, yP)
    fmt.Println(points)

此处,你将字符串转为数字,并追加到二维切片points中。

CSVplot.go最后一部分代码如下:

    dimensions := 2
    persist := true
    debug := false
    plot, _ := glot.NewPlot(dimensions, persist, debug)

    plot.SetTitle("Using Glot with CSV data")
    plot.SetXLabel("X-Axis")
    plot.SetYLabel("Y-Axis")
    style := "circle"
    plot.AddPointGroup("Circle:", style, points)
    plot.SavePlot("output.png")
}

在前面的go代码中,你了解了如何使用Glot库及其Glot.SavePlot()函数创建PNG文件。

可以猜到,在编译和执行CSVplot.go之前,需要下载Glot Go库,它需要从Unix shell执行以下命令:

$ go get github.com/Arafatk/glot

你可以通过查看~/go目录查看当前命令的执行结果:

$ ls -l ~/go/pkg/darwin_amd64/github.com/Arafatk/
total 240
-rw-r--r-- 1 mtsouk staff 119750 Jan 22 22:12 glot.a
$ ls -l ~/go/src/github.com/Arafatk/glot/
total 120
-rw-r--r--  1 mtsouk  staff   1818   Jan  22 22:12 README.md
-rw-r--r--  1 mtsouk  staff   6092   Jan  22 22:12 common.go
-rw-r--r--  1 mtsouk  staff    552   Jan  22 22:12 common_test.go
-rw-r--r--  1 mtsouk  staff   3162   Jan  22 22:12 core.go
-rw-r--r--  1 mtsouk  staff    138   Jan  22 22:12 core_test.go
-rw-r--r--  1 mtsouk  staff   3049   Jan  22 22:12 function.go
-rw-r--r--  1 mtsouk  staff    511   Jan  22 22:12 function_test.go
-rw-r--r--  1 mtsouk  staff   4955   Jan  22 22:12 glot.go
-rw-r--r--  1 mtsouk  staff    220   Jan  22 22:12 glot_test.go
-rw-r--r--  1 mtsouk  staff  10536   Jan  22 22:12 pointgroup.go
-rw-r--r--  1 mtsouk  staff    378   Jan  22 22:12 pointgroup_test.go

包含要绘制的点的CSV数据文件具有以下格式:

$ cat /tmp/dataFile
1,2
2,3
3,3
4,4
5,8
6,5
-1,12
-2,10
-3,10
-4,10

执行CSVplot.go会产生如下的输出:

$ go run CSVplot.go /tmp/doesNoExits
Cannot stat /tmp/doesNoExits
$ go run CSVplot.gp /tmp/dataFile
[[1 2 3 4 5 6 -1 -2 -3 -4] [2 3 3 4 8 5 12 10 10 10]]

Last updated