我正在尝试学习 Go(或 Golang),但似乎无法正确学习。我有 2 个文本文件,每个文件都包含一个单词列表。我正在尝试计算两个文件中存在的单词数量。到目前为止,这是我的代码:package mainimport ( "fmt" "log" "net/http" "bufio")func stringInSlice(str string, list []string) bool { for _, v := range list { if v == str { return true } } return false}func main() { // Texts URL var list = "https://gist.githubusercontent.com/alexcesaro/c9c47c638252e21bd82c/raw/bd031237a56ae6691145b4df5617c385dffe930d/list.txt" var url1 = "https://gist.githubusercontent.com/alexcesaro/4ebfa5a9548d053dddb2/raw/abb8525774b63f342e5173d1af89e47a7a39cd2d/file1.txt" //Create storing arrays var buffer [2000]string var bufferUrl1 [40000]string // Set a sibling counter var sibling = 0 // Read and store text files wordList, err := http.Get(list) if err != nil { log.Fatalf("Error while getting the url : %v", err) } defer wordList.Body.Close() wordUrl1, err := http.Get(url1) if err != nil { log.Fatalf("Error while getting the url : %v", err) } defer wordUrl1.Body.Close() streamList := bufio.NewScanner(wordList.Body) streamUrl1 := bufio.NewScanner(wordUrl1.Body) streamList.Split(bufio.ScanLines) streamUrl1.Split(bufio.ScanLines) var i = 0; var j = 0; //Fill arrays with each lines for streamList.Scan() { buffer[i] = streamList.Text() i++ } for streamUrl1.Scan() { bufferUrl1[j] = streamUrl1.Text() j++ } //ERROR OCCURRING HERE : // This code if i'm not wrong is supposed to compare through all the range of bufferUrl1 -> bufferUrl1 values with buffer values, then increment sibling and output FIND for v := range bufferUrl1{ if stringInSlice(bufferUrl1, buffer) { sibling++ fmt.Println("FIND") } } // As a testing purpose thoses lines properly paste both array // fmt.Println(buffer) // fmt.Println(bufferUrl1)}
1 回答

人到中年有点甜
TA贡献1895条经验 获得超7个赞
bufferUrl1是一个数组:[4000]string。您打算使用v( 中的每个字符串bufferUrl1)。但实际上,您打算使用第二个变量——第一个变量是在下面的代码中使用_.
类型[2000]string不同于[]string. 在 Go 中,数组和切片是不一样的。阅读Go Slices:用法和内部结构。我已经使用 make 更改了两个变量声明以使用具有相同初始长度的切片。
这些是您需要进行编译的更改。
声明:
// Create storing slices
buffer := make([]string, 2000)
bufferUrl1 := make([]string, 40000)
和第 69 行的循环:
for _, s := range bufferUrl1 {
if stringInSlice(s, buffer) {
sibling++
fmt.Println("FIND")
}
}
作为旁注,考虑使用映射而不是切片来buffer实现更高效的查找,而不是在stringInSlice.
https://play.golang.org/p/UcaSVwYcIw修复了以下评论(您将无法从 Playground 发出 HTTP 请求)。
- 1 回答
- 0 关注
- 177 浏览
添加回答
举报
0/150
提交
取消