태그 보관물: 코드

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