我有一条消息流进入Go频道,其中大部分都是:
T: added package to graph: acl-devel/2.2.52_4/armv6l-musl
T: added package to graph: rofs-filtered/1.7_1/x86_64-musl
T: added package to graph: rofs-filtered/1.7_1/HOST
T: added package to graph: libshout/2.4.1_1/i686
T: added package to graph: mate-terminal/1.18.1_1/armv6l
T: added package to graph: bullet-devel/2.86.1_1/x86_64-musl
T: added package to graph: bullet-devel/2.86.1_1/HOST
T: added package to graph: cubietruck-uboot/2016.11_1/armv6l-musl
T: added package to graph: libfontenc/1.1.3_1/i686-musl
T: added package to graph: apk-tools/2.8.1_1/x86_64
T: added package to graph: virtualbox-ose/5.1.28_1/armv7l-musl
T: added package to graph: acl-devel/2.2.52_4/armv7l
T: added package to graph: apk-tools/2.8.1_1/x86_64-musl
T: added package to graph: tzutils/2017c_1/x86_64-musl
T: added package to graph: python-argh/0.26.2_1/noarch
T: added package to graph: tzutils/2017c_1/HOST
我希望能够有效地将上述字符串逐行组合,但不会丢失任何信息。这是为了打印到IRC频道,所以我不想触发洪水警告。要做到这一点,我想按摩以上类似于下面的内容:
T: added package to graph: rofs-filtered/1.7_1/{x86_64-musl,HOST}
T: added package to graph: libshout/2.4.1_1/i686
T: added package to graph: mate-terminal/1.18.1_1/armv6l
T: added package to graph: bullet-devel/2.86.1_1/{x86_64-musl,HOST}
T: added package to graph: cubietruck-uboot/2016.11_1/armv6l-musl
T: added package to graph: libfontenc/1.1.3_1/i686-musl
T: added package to graph: apk-tools/2.8.1_1/{x86_64,x86_64-musl}
T: added package to graph: virtualbox-ose/5.1.28_1/armv7l-musl
T: added package to graph: acl-devel/2.2.52_4/{armv6l-musl,armv7l}
T: added package to graph: tzutils/2017c_1/{x86_64-musl,HOST}
T: added package to graph: python-argh/0.26.2_1/noarch
虽然仍然有很多输出和消息,但报告的大部分是大约10-12行,上面有公共前缀,其中散布着执行上述操作的多个线程的输出(因此上述数据中的重复次数较少) ,许多线程和数据是约2秒的快照。
如何在Go中压缩多行以加入它们的公共前缀?
答案 0 :(得分:1)
这是一个可能的解决方案。如果需要,可以在append()命令之前检查重复项。
https://play.golang.org/p/XodCgl1fa5
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
input := `T: added package to graph: acl-devel/2.2.52_4/armv6l-musl
T: added package to graph: rofs-filtered/1.7_1/x86_64-musl
T: added package to graph: rofs-filtered/1.7_1/HOST
T: added package to graph: libshout/2.4.1_1/i686
T: added package to graph: mate-terminal/1.18.1_1/armv6l
T: added package to graph: bullet-devel/2.86.1_1/x86_64-musl
T: added package to graph: bullet-devel/2.86.1_1/HOST
T: added package to graph: cubietruck-uboot/2016.11_1/armv6l-musl`
m := make(map[string][]string)
s := bufio.NewScanner(strings.NewReader(input))
for s.Scan() {
t := s.Text()
i := strings.LastIndex(t, "/")
p := t[:i+1]
last := t[i+1 : len(t)]
m[p] = append(m[p], last)
}
for k, v := range m {
fmt.Print(k, "{", strings.Join(v, ","), "}", "\n")
}
}