为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
人到中年有点甜 2022-08-01 10:47:47
我有下面的代码,即读取根目录中的所有文件,根据给定的单词扫描它们以查找特定单词,并报告每个文件中找到的单词。我遇到的问题是,如果一个wod被提及的次数超过一个(即在文件中的不同位置),它将被报告与它出现一样多,我需要将其重新排序为唯一的,因此排除重复项。例如,在文件中:txtregexregextxtI'm an engineer not a doctorreally, I'm not a doctor这个词被报告两次,而我需要让它成为唯一的,即。它足以让我知道它在文件中。我的代码是:doctorpackage mainimport (    "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)            }        }    }}
查看完整描述

1 回答

?
红糖糍粑

TA贡献1815条经验 获得超6个赞

你可以从你的匹配从 a 转换到 a 使用: https://godoc.org/github.com/golang-collections/collections/set[]stringSet

这样:


package main


import (

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

            // }

        }

    }

}


查看完整回答
反对 回复 2022-08-01
  • 1 回答
  • 0 关注
  • 213 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号