如何使用Golang自定义扫描程序字符串文字并扩展内存以将整个文件
发布时间:2020-12-16 09:27:33 所属栏目:大数据 来源:网络整理
导读:我一直试图弄清楚如何实现我原先认为的简单程序. 我有一个引号的文本文件,都用’$$’分隔 我希望程序解析引用文件并随机选择3个引号来显示和标准输出. 文件中有1022个引号. 当我尝试拆分文件时,我收到此错误: ?失踪 ‘ 我似乎无法弄清楚如何使用字符串文字
我一直试图弄清楚如何实现我原先认为的简单程序.
我有一个引号的文本文件,都用’$$’分隔 我希望程序解析引用文件并随机选择3个引号来显示和标准输出. 文件中有1022个引号. 当我尝试拆分文件时,我收到此错误: 我似乎无法弄清楚如何使用字符串文字分配$$,我不断得到: 这是自定义扫描仪: onDollarSign := func(data []byte,atEOF bool) (advance int,token []byte,err error) { for i := 0; i < len(data); i++ { //if data[i] == "$$" { # this is what I did originally //if data[i:i+2] == "$$" { # (mismatched types []byte and string) //if data[i:i+2] == `$$` { # throws (mismatched types []byte and string) // below throws syntax error: unexpected $AND missing ' if data[1:i+2] == '$$' { return i + 1,data[:i],nil } } 如果我只使用一个$,字符串文字工作正常. 由于某种原因,只有71个引号被加载到引号切片中.我不知道如何扩展.允许所有1022引号存储在内存中. 我一直在努力想弄清楚如何做到这一点.这就是我现在所拥有的: package main import ( "bufio" "fmt" "log" "math/rand" "os" "time" ) func main() { rand.Seed(time.Now().UnixNano()) // Try changing this number! quote_file,err := os.Open("/Users/bryan/Dropbox/quotes_file.txt") if err != nil { log.Fatal(err) } scanner := bufio.NewScanner(quote_file) // define split function onDollarSign := func(data []byte,err error) { for i := 0; i < len(data); i++ { if data[i] == '$$' { return i + 1,nil } } fmt.Print(data) return 0,data,bufio.ErrFinalToken } scanner.Split(onDollarSign) var quotes []string // I think this will scan the file and append all the parsed quotes into quotes for scanner.Scan() { quotes = append(quotes,scanner.Text()) } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr,"reading input:",err) } fmt.Print(len(quotes)) fmt.Println("quote 1:",quotes[rand.Intn(len(quotes))]) fmt.Println("quote 2:",quotes[rand.Intn(len(quotes))]) fmt.Println("quote 3:",quotes[rand.Intn(len(quotes))]) } 解决方法
如果你最终阅读整个文件,使用扫描仪有点令人费解.我阅读了整个文件,然后将其拆分为引号列表:
package main import ( "bytes" "io/ioutil" "log" "math/rand" "os" ) func main() { // Slurp file. contents,err := ioutil.ReadFile("/Users/bryan/Dropbox/quotes_file.txt") if err != nil { log.Fatal(err) } // Split the quotes separator := []byte("$$") // Convert string to []byte quotes := bytes.Split(contents,separator) // Select three random quotes and write them to stdout for i := 0; i < 3; i++ { n := rand.Intn(len(quotes)) quote := quotes[n] os.Stdout.Write(quote) os.Stdout.Write([]byte{'n'}) // new line,if necessary } } 如果在读取文件之前选择了三个引号,则使用扫描仪是有意义的;然后你可以在到达最后一个报价后停止阅读. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |