gpt4 book ai didi

go - 如何在列表中丢弃带有某些字符串的行并输出到新列表

转载 作者:行者123 更新时间:2023-12-01 22:37:25 38 4
gpt4 key购买 nike

我有一个从XML网站下载的列表。我试图通过丢弃包含特定字符串的行并构建不包含字符串的行的相同类型的列表来过滤列表。
我的struct类型具有另一个struct
我正在尝试使用regexpreplaceall,但无法使用replaceall

func (*Regexp) ReplaceAll
func (re *Regexp) ReplaceAll(src, repl []byte) []byte

可能存在一种完全简单的方法来将列表过滤到我在某处缺少的新列表,但是到目前为止,我发现这是最接近的解决方案。请分享其他grep和删除行到新列表的方式。该列表是正文的一个字节,并以xml格式下载。

type PeopleList struct {
Peoples []Person `xml:"peoples>person"`
}

type Person struct {
ADD string `xml:"add,attr"`
Loc string `xml:"loc,attr"`
Har string `xml:"har,attr"`
Name string `xml:"name,attr"`
Country string `xml:"country,attr"`
Num string `xml:"num,attr"`
ADD2 string `xml:"add2,attr"`
Distance float64

func fetchPeopleList(userinfo Userinfo) PeopleList {
var p byte
jam, err := http.Get(string(peoplelisturl))
iferror (err)
body, err := ioutil.ReadAll(jam.Body)
peeps := body
reg := regexp.MustCompile("(?m)[\r\n]+^.*BAD:.*$")
rep := reg.ReplaceAll(peeps, p) // Here fails probably because of my syntax. Error: cannot use p (variable of type byte) as []byte value in argument to re.ReplaceAll

fmt.Println(rep)
iferror (err)
defer jam.Body.Close()

最后,我想要一个与第一个格式相同的新列表,只是没有包含字符串的行。

最佳答案

您的问题是说您要“丢弃行”,但是顾名思义,Replace / ReplaceAll用于替换匹配的模式。您的正则表达式也是一个简单的子字符串匹配项,因此显而易见的解决方案似乎是逐行读取文件,并且-如您的标题所说-丢弃包含子字符串的行。

func fetchPeopleList(userinfo Userinfo) PeopleList {
jam, err := http.Get(string(peoplelisturl))
iferror (err)
br := bufio.NewReader(jam.Body)
defer jam.Body.Close()
for {
line,err := br.ReadString('\n')
if !strings.Contains(line, "BAD:") {
fmt.Println(line) // or whatever you want to do with non-discarded lines
}
if err != nil {
break
}
}

关于go - 如何在列表中丢弃带有某些字符串的行并输出到新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58768618/

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