gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:37:16 24 4
gpt4 key购买 nike

我一直在努力弄清楚如何实现我原先认为会很简单的程序。我有一个由“$$”分隔的引文文本文件

我想让程序解析报价文件并随机选择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 个引语被加载到引语 slice 中。我不确定如何展开。允许所有 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, 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))])
}

最佳答案

如果您最终要阅读整个文件,则使用扫描仪会有些费解。我会阅读整个文件,然后将其简单地分成引号列表:

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

如果您在阅读文件之前选择了三个引号,那么使用扫描仪是有意义的;然后你可以在读到最后一个报价后停止阅读。

关于go - 如何使用 Golang 自定义扫描器字符串文字和扩展内存将整个文件加载到内存中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46609805/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com