🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## 实例 ~~~ package main import ( "os" "bufio" "time" "io" "github.com/axgle/mahonia" "strings" "fmt" ) func main() { file, _ := os.Open("G:\\pachong\\001.txt") defer file.Close() //准备一个优质数据文件 goodFile, _ := os.OpenFile("G:\\pachong\\001.txtkaifang_good.txt", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644) defer goodFile.Close() //准备一个错误数据文件 badFile, _ := os.OpenFile("G:\\pachong\\kaifang_bad.txt", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644) defer badFile.Close() //缓冲读取 reader := bufio.NewReader(file) //记录用时 t := time.Now() for { //按行读取 lineBytes, _, err := reader.ReadLine() if err == io.EOF { break } gbkStr := string(lineBytes) // 编码 lineStr := ConvertEncoding(gbkStr, "GBK") //将行数据,按照逗号拆分 fields := strings.Split(lineStr, ",") if len(fields) > 2 && len(fields[1]) == 18 { //正确的数据 goodFile.WriteString(lineStr + "\n") fmt.Println("Good:", lineStr) } else { //劣质文件 badFile.WriteString(lineStr + "\n") fmt.Println("Bad:", lineStr) } } // 返回一个时间差 end := time.Since(t) fmt.Println("程序用时:", end) } //处理乱码 func ConvertEncoding(srcStr string, encoding string) (dstStr string) { enc := mahonia.NewDecoder(encoding) utfStr := enc.ConvertString(srcStr) dstStr = utfStr return } ~~~