繁体   English   中英

编写 function,它接受输入参数 sentence 和 n(整数类型),并返回包含从给定句子生成的 N-gram 的列表

[英]write function which takes input parameters sentence and n (type integer), and returns a list that contains N-gram generated from the given sentence

编写一个 function construct_ngrams(sentence, n),它接受输入参数 sentence(字符串类型)和 n(整数类型),并返回包含从给定句子生成的 N-gram 的列表。 如果无法生成这样的 N-gram(考虑这些情况),那么它只会返回一个空列表。

到目前为止我有这个

def construct_ngrams(sentence, n):
    """Returns a list that counts N-gram generated from the given sentence"""
    words = sentence.split()
    
    if n == 0 or n > len(words) -1:
        return []
    ngram = []
    
    for i in range(n):
       ngram.append(words[i:i+n])
    
   return ngram

然而,这并没有通过以下测试:

ngrams = construct_ngrams('this is another long sentence for testing', 6)
print(ngrams)

它给出: [['this', 'is', 'another', 'long', 'sentence', 'for'], ['is', 'another', 'long', 'sentence', 'for', 'testing'], ['another', 'long', 'sentence', 'for', 'testing'], ['long', 'sentence', 'for', 'testing'], ['sentence', 'for', 'testing'], ['for', 'testing']]

而不是: [['this', 'is', 'another', 'long', 'sentence', 'for'], ['is', 'another', 'long', 'sentence', 'for', 'testing']]

谁能帮我解决这个问题?

我在你的代码中发现了几个错误,首先“return”只能用在 function 的末尾。你可以将 ngram=[] 放在 function 之外,而不是放在 if 语句中。 这是修改后的代码,希望对你有帮助。

def construct_ngrams(sentence, n):
    words = sentence.split()
    ngram=[]
    if n == 0 or n > len(words) -1:
        pass
    else:
        for i in range(len(words)-n+1):
            ngram.append(words[i:i+n])
    return ngram

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM