github.com/easysoft/zendata@v0.0.0-20240513203326-705bd5a7fd67/cmd/test/others/func/import/poetry-ancient.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "os" 6 "path/filepath" 7 "strings" 8 9 "github.com/easysoft/zendata/cmd/test/others/func/comm" 10 "github.com/easysoft/zendata/cmd/test/others/func/model" 11 fileUtils "github.com/easysoft/zendata/pkg/utils/file" 12 "github.com/snowlyg/helper/dir" 13 ) 14 15 func main() { 16 filePath := "/Users/aaron/work/zentao/product/zd/行业数据/古诗词(分类)" 17 18 var files []string 19 filepath.Walk(filePath, func(path string, info os.FileInfo, err error) error { 20 files = append(files, path) 21 return nil 22 }) 23 24 tableName := model.PoetryAncient{}.TableName() 25 db := comm.GetDB() 26 err := db.Exec(fmt.Sprintf(comm.TruncateTable, tableName)).Error 27 if err != nil { 28 panic(err) 29 } 30 31 tableName2 := model.PoetryCategory{}.TableName() 32 err = db.Exec(fmt.Sprintf(comm.TruncateTable, tableName2)).Error 33 if err != nil { 34 panic(err) 35 } 36 37 for _, file := range files { 38 if !dir.IsFile(file) || strings.Index(file, ".txt") < 0 { 39 continue 40 } 41 42 content := fileUtils.ReadFile(file) 43 44 for _, line := range strings.Split(content, "\n") { 45 col1 := strings.TrimSpace(line) 46 47 name := strings.TrimRight(filepath.Base(file), ".txt") 48 cate := model.PoetryCategory{ 49 EnName: name, 50 Name: name, 51 } 52 53 cateOld := model.PoetryCategory{} 54 db.Where("en_name = ?", name).First(&cateOld) 55 id := cateOld.Id 56 if id == 0 { 57 db.Save(&cate) 58 id = cate.Id 59 } 60 61 po := model.PoetryAncient{ 62 CategoryId: id, 63 Content: col1, 64 } 65 66 if po.Content != "" { 67 db.Save(&po) 68 } 69 } 70 } 71 }