从字符串生成n-gram

4

我需要列出从字符串开头开始的所有-gram列表,每个整数从1到M。然后返回一个由M个这样的列表组成的元组。

    def letter_n_gram_tuple(s, M):
        s = list(s)
        output = []
    for i in range(0, M+1):

        output.append(s[i:])

    return(tuple(output))

使用 letter_n_gram_tuple("abcd", 3) 输出结果应为:

(['a', 'b', 'c', 'd'], ['ab', 'bc', 'cd'], ['abc', 'bcd']))

然而,我的输出结果是:
(['a', 'b', 'c', 'd'], ['b', 'c', 'd'], ['c', 'd'], ['d']).

我应该使用字符串切片,然后将切片保存到列表中吗?


你已经获得了15个声望值,给每个人点赞是值得的。 - U13-Forward
4个回答

2
你可以使用嵌套的for循环,第一个for循环用于n-gram,第二个用于切分字符串。"Original Answer"的翻译是"最初的回答"。
def letter_n_gram_tuple(s, M):
    output = []

    for i in range(1, M + 1):
        gram = []
        for j in range(0, len(s)-i+1):
            gram.append(s[j:j+i])
        output.append(gram)

    return tuple(output)

或者使用列表推导式仅用一行代码实现:

output = [[s[j:j+i] for j in range(0, len(s)-i+1)] for i in range(1, M + 1)]

或者使用more_itertools中的windowed函数:最初的回答
import more_itertools
output = [list(more_itertools.windowed(s, i)) for i in range(1, M + 1)]

test and output:

print(letter_n_gram_tuple("abcd", 3))
(['a', 'b', 'c', 'd'], ['ab', 'bc', 'cd'], ['abc', 'bcd'])

2
你需要再添加一个 for 循环来迭代字母或字符串:

最初的回答
def letter_n_gram_tuple(s, M):
    output = []
    for i in range(0, M):
        vals = [s[j:j+i+1] for j in range(len(s)) if len(s[j:j+i+1]) == i+1]
        output.append(vals)

    return tuple(output)

print(letter_n_gram_tuple("abcd", 3))

输出:

(['a', 'b', 'c', 'd'], ['ab', 'bc', 'cd'], ['abc', 'bcd'])

2
请使用以下函数:

function:

def letter_n_gram_tuple(s, M):
    s = list(s)
    output = [s]
    for i in range(M + 1):
        output.append([''.join(sorted(set(a + b), key=lambda x: (a + b).index(x))) for a, b in zip(output[-1], output[-1][1:])])
    return tuple(filter(lambda x: len(x) > 1, output))

最初的回答
现在是这样的:
print(letter_n_gram_tuple('abcd',3))

返回:

最初的回答
(['a', 'b', 'c', 'd'], ['ab', 'bc', 'cd'], ['abc', 'bcd'])

2
def n_grams(word,max_size):
    i=1
    output=[]
    while i<= max_size:
        index = 0
        innerArray=[]
        while index < len(word)-i+1:
            innerArray.append(word[index:index+i])
            index+=1
        i+=1
        output.append(innerArray)
        innerArray=[]
    return tuple(output)
print(n_grams("abcd",3))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接