変換方法のカスタマイズ
配列transforms
の内容をハードコードするのではなく、テキストファイルやデータベースなどから読み込んでカスタマイズできるようにしてみましょう。
準備
- 同じディレクトリ位置に
word.txt
を用意しておく
word.txt
get*
go*
lets*
*web
*ty
*ing
*done
we*
my*
you*
main.go
package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"strings"
"time"
"errors"
)
const otherWord = "*"
var ErrFileNotFound = errors.New("ファイルが見つかりませんでした")
func makeWords() ([]string) {
var transforms = []string{
otherWord,
otherWord,
otherWord,
otherWord,
otherWord + "app",
otherWord + "site",
otherWord + "time",
"get" + otherWord,
"go" + otherWord,
"lets" + otherWord,
}
return transforms
}
func makeWords_FromFile() ([]string, error) {
file, err := os.Open("word.txt")
var transforms = []string{}
if err != nil {
fmt.Println("word.txt not found!")
return nil, ErrFileNotFound
}else{
var words = bufio.NewScanner(file)
for words.Scan() {
transforms = append(transforms, words.Text())
}
}
return transforms, nil
}
func main(){
transforms, err := makeWords_FromFile()
if err != nil {
transforms = makeWords()
}
rand.Seed(time.Now().UTC().UnixNano())
s := bufio.NewScanner(os.Stdin)
for s.Scan() {
t := transforms[rand.Intn(len(transforms))]
fmt.Println(strings.Replace(t, otherWord, s.Text(), -1))
}
}