태그 보관물: 개발

Go언어 CSV 파일 쓰기 – Golang writing a csv file

Go언어로 CSV 파일을 만드는 코드입니다.

데이터 과학 업무를 하다보면 데이터처리를 할 때 CSV 파일을 빈번하게 읽거나 만드는 일이 있습니다.

특히 사이즈가 큰 파일은 처리 속도도 매우 중요하기 때문에 Go나 Rust, C++로 처리해야 할 수 있습니다.

Go언어로 CSV 파일을 처리하는 방법을 알아 두면 그럴 때 편하게 쓸 수 있습니다.

package main

import (
	"encoding/csv"
	"fmt"
	"os"
)

func main() {
	csvFile, err := os.Create("output.csv")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	defer csvFile.Close()

	records := [][]string{{"item1", "value1"}, {"item2", "value2"}, {"item3", "value3"}}

	writer := csv.NewWriter(csvFile)
	for _, record := range records {
		err := writer.Write(record)
		if err != nil {
			fmt.Println("Error:", err)
			return
		}
	}
	writer.Flush()
}

When you work on data science. you frequently deal with CSV files. and sometimes the CSV files are so big. in that case, processing speed is also important.

So you need to know how can you deal with CSV files with high-performance computer languages like Go, Rust, C++.

Go언어 FastText 모델 로딩해서 예측 수행하기 – Golang do prediction with built model

Facebook FastText로 만든 분류모델 (supervised model)을 로딩해서 prediction하는 간단한 코드입니다.

FastText 모델은 Python으로도 로딩해서 사용할 수 있습니다.

하지만 Python은 멀티쓰레드를 사용하기가 어려우니 빠른 속도를 위해서 Go언어나 다른 언어를 써야 할 때가 있으니 알아두면 좋습니다.

// FastText prediction
package main

import (
	"fmt"
	fasttext "github.com/bountylabs/go-fasttext"
)

func main() {
	model := fasttext.Open("//model/fasttext01.bin")
	fmt.Println("Prediction...")
	predictResult, err := model.Predict("분류할 입력 텍스트입니다.")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Printf("Label: %s, Prob: %fs\n", predictResult[0].Label, predictResult[0].Probability)
}

FastText provide a command-line process to make a model. to apply the model to production, you may want write code for processing particular logic.

so, you need to know how cat load prebuilt FastText model and process prediction with Go language

Go언어 명령행 인수 처리 – Golang getting arguments from command line

Go언어에서 명령행 인수를 처리하는 방법입니다.

몇가지 방법이 더 있지만 여기에서는 flag 모듈를 사용합니다.

package main

import (
	"flag"
	"fmt"
)

func main() {
	file := flag.String("file", "default.txt", "Input file")
	maxcpu := flag.Int("maxcpu", 10, "Max CPU Count")
	isForce := flag.Bool("force", false, "Run force")

	flag.Parse()

	// 포인터 변수이므로 앞에 * 를 붙어 deference 해줘야 한다.
	fmt.Printf("file: %s\n", *file)
	fmt.Printf("maxcpu: %d\n", *maxcpu)
	fmt.Printf("force: %t\n", *isForce)
}

/* 테스트
C> go build exam_arguments.go
C> exam_arguments -file=test.csv -maxtrial=5 -force=true
*/

Go언어 csv.gz 읽기

csv파일은 gzip 압축이 되는 경우가 많습니다.

압축을 따로 풀지않고 gz 압축된 csv 파일을 직접 처리하는 것이 더 편할때가 많아졌습니다.

Go언어에서 gzip으로 압축된 csv 파일을 읽는 방법입니다.

package main

import (
	"compress/gzip"
	"encoding/csv"
	"fmt"
	"log"
	"os"
)

func main() {
	file, err := os.Open("data.csv.gz")

	if err != nil {
		log.Fatal(err)
	}

	defer file.Close()

	gzipReader, err := gzip.NewReader(file)

	if err != nil {
		log.Fatal(err)
	}

	defer gzipReader.Close()

	csvReader := csv.NewReader(gzipReader)
	record, err := csvReader.Read()

	if err != nil {
		log.Fatal(err)
	}

	for _, v := range record {
		fmt.Println(v)
	}
}