首页 > 解决方案 > 如何分割/拆分文件中的单词

问题描述

我有一个包含很多单词的文件,我必须拆分其中一部分已经存在或在扫描文件期间出现的单词:

文件中的一些单词是

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

标签: gosplit

解决方案


对于给定的输入,以下会有所帮助。

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
}

你可以在这里找到工作代码:操场


推荐阅读