go - 如何分割/拆分文件中的单词
问题描述
我有一个包含很多单词的文件,我必须拆分其中一部分已经存在或在扫描文件期间出现的单词:
文件中的一些单词是
member
members
membership
memberships
我已经尝试过了,但我希望第一行[i](这是a)继续循环下一个单词
func Split(lines []string) string {
for i := 0; i < len(lines)-1; i++ { // position of words
j := i + 1
fmt.Println(lines[i], lines[j])
if strings.ContainsAny(lines[j], lines[i]) {
s := strings.Split(dictionary[j], dictionary[i])
fmt.Println(dictionary[i], ".", s)
}
}
...
}
但它只输出
member
member.s
members.hip
membership.s
我想要的输出:
member
member.s
member.ship
members.hip
member.ships
members.hips
解决方案
对于给定的输入,以下会有所帮助。
func splitSegmant(prev string, cur string) string {
if len(cur) < len(prev) || cur[:len(prev)] != prev {
return ""
}
return fmt.Sprintf("%s.%s", cur[:len(prev)], cur[len(prev):])
}
func Split(lines []string) []string {
splits := []string{lines[0]}
for i := 0; i < len(lines); i++ {
for j := 0; j < i; j++ {
split := splitSegmant(lines[j], lines[i])
if split != "" {
splits = append(splits, split)
}
}
}
return splits
}
你可以在这里找到工作代码:操场
推荐阅读
- javascript - 运行 npm start 命令时 React Redux 项目的语法错误
- amazon-web-services - 使用密码而不是 pem 密钥启用 SSH
- binding - Native Control 上的双向绑定导致 Xamarin Forms 跨平台严重崩溃
- c# - 试图确定一个应用程序是否使用 web api 2 或其他东西?
- javascript - 网页中的 Nodejs 模块
- arduino - IrRemote lib 可使用的 ir 代码为十六进制
- python - python:如何在 yaml 文件中添加新的键和值
- c# - 使用值转换器将复选框绑定到标签字体粗细
- php - 如何在表格 PHP 的页脚中创建一个 outosum 和 average 函数
- php - Laravel Eloquent 相关模型必须匹配两个外键