在 FindAllString 正则表达式中排除重复项

我有下面的代码,即读取根目录中的所有文件,根据给定的单词扫描它们以查找特定单词,并报告每个文件中找到的单词。我遇到的问题是,如果一个wod被提及的次数超过一个(即在文件中的不同位置),它将被报告与它出现一样多,我需要将其重新排序为唯一的,因此排除重复项。例如,在文件中:txtregexregextxt


I'm an engineer not a doctor

really, I'm not a doctor

这个词被报告两次,而我需要让它成为唯一的,即。它足以让我知道它在文件中。我的代码是:doctor


package main


import (

    "fmt"

    "io/ioutil"

    "log"

    "path/filepath"

    "regexp"

    "strings"

)


func main() {

    files, err := ioutil.ReadDir(".")

    if err != nil {

        log.Fatal(err)

    }


    p := []string{}

    p = append(p, "engineer")

    p = append(p, "doctor")

    p = append(p, "chemical (permit)")

    skills := strings.Join(p, "|")


    fmt.Println(skills)

    re := regexp.MustCompile(`(?i)` + skills)


    for _, file := range files {

        if strings.ToLower(filepath.Ext(file.Name())) == ".txt" {

            fmt.Println(file.Name())


            b, err := ioutil.ReadFile(file.Name()) // just pass the file name

            if err != nil {

                fmt.Print(err)

            }

            //fmt.Println(b) // print the content as 'bytes'


            str := string(b) // convert content to a 'string'

            matches := re.FindAllString(str, -1)

            fmt.Println(matches, len(matches))


            for _, j := range matches {

                fmt.Println(j)

            }

        }

    }

}


人到中年有点甜
浏览 214回答 1
1回答

红糖糍粑

你可以从你的匹配从 a 转换到 a 使用: https://godoc.org/github.com/golang-collections/collections/set[]stringSet这样:package mainimport (    "fmt"    "io/ioutil"    "log"    "path/filepath"    "regexp"    "strings"    "github.com/golang-collections/collections/set")func main() {    files, err := ioutil.ReadDir(".")    if err != nil {        log.Fatal(err)    }    p := []string{}    p = append(p, "engineer")    p = append(p, "doctor")    p = append(p, "chemical (permit)")    skills := strings.Join(p, "|")    fmt.Println(skills)    re := regexp.MustCompile(`(?i)` + skills)    for _, file := range files {        if strings.ToLower(filepath.Ext(file.Name())) == ".txt" {            fmt.Println(file.Name())            b, err := ioutil.ReadFile(file.Name()) // just pass the file name            if err != nil {                fmt.Print(err)            }            //fmt.Println(b) // print the content as 'bytes'            str := string(b) // convert content to a 'string'            matches := re.FindAllString(str, -1)            matchesSet := set.New(matches...)            matchesSet.Do(func print(s string) {              fmt.Println(s)            }            // fmt.Println(matches, len(matches))            // for _, j := range matches {            //     fmt.Println(j)            // }        }    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go