计算相似的数组值

Count similar array value

我正在尝试学习 Go(或 Golang),但似乎学不会。我有 2 个文本文件,每个文件都包含一个单词列表。我正在尝试计算两个文件中出现的字数。

到目前为止,这是我的代码:

package main

import (
    "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)

}

但是现在,我的构建甚至没有成功。我只收到这条消息:

.\hello.go:69: cannot use bufferUrl1 (type [40000]string) as type string in argument to stringInSlice
.\hello.go:69: cannot use buffer (type [2000]string) as type []string in argument to stringInSlice
  1. bufferUrl1 是一个数组:[4000]string。您打算使用 v(每个 bufferUrl1 中的字符串)。但事实上,你打算用第二个 变量——第一个变量是在代码中被忽略的索引 下面使用 _.
  2. 类型 [2000]string 不同于 []string。在 Go 中,数组和切片是不一样的。阅读Go Slices: usage and internals。我已经使用 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 请求)。