dongnan1899 2017-10-06 16:07
浏览 45
已采纳

如何使用Golang自定义扫描器字符串文字并扩展内存以将整个文件加载到内存中?

I have been trying to figure out how to implement what I originally thought would be a simple program. I have a text file of quotations that are all separated by ‘$$’

I want the program to parse the quotation file and randomly select 3 quotes to display and standard output.

There are 1022 quotes in the file.

When I attempt to split the file I get this error: missing '

I can’t seem to figure out how to assign $$ with a string literal, I keep getting:
missing '

This is the custom scanner:

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  
        }  
    }  

The string literal works fine if I only use one $.

For some reason only 71 quotations are loaded into the quotes slice. I'm not sure how to expand. To allow all 1022 quotes to be stored in memory.

I've been having a really difficult time trying to figure out how to do this. this is what I have right now:

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, atEOF bool) (advance int, token []byte, err error) {  
        for i := 0; i < len(data); i++ {  
            if data[i] == '$$' {  
                return i + 1, data[:i], 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))])  
}  
  • 写回答

4条回答 默认 最新

  • doumao1917 2017-10-12 14:19
    关注

    Using a scanner if you end up reading the whole file anyway is kind of convoluted. I'd read the whole file and then simply split it into the list of 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{'
    '}) // new line, if necessary
        }
    }
    

    Using a scanner would make sense if you selected three quotes before reading the file; then you can stop reading after you have reached the last quote.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效