[英]write function which takes input parameters sentence and n (type integer), and returns a list that contains N-gram generated from the given sentence
write a function construct_ngrams(sentence, n) which takes input parameters sentence (type string) 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 的列表。 If no such N-gram could be generated (think about the cases), then it simply returns an empty list.如果无法生成这样的 N-gram(考虑这些情况),那么它只会返回一个空列表。
I have this so far到目前为止我有这个
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
however this does not pass the following test:然而,这并没有通过以下测试:
ngrams = construct_ngrams('this is another long sentence for testing', 6)
print(ngrams)
it gives: [['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'], ['another', 'long', 'sentence', 'for', 'testing'], ['long', 'sentence', 'for', 'testing'], ['sentence', 'for', 'testing'], ['for', 'testing']]
rather than: [['this', 'is', 'another', 'long', 'sentence', 'for'], ['is', 'another', 'long', 'sentence', 'for', 'testing']]
而不是: [['this', 'is', 'another', 'long', 'sentence', 'for'], ['is', 'another', 'long', 'sentence', 'for', 'testing']]
any one be able to help me fix this?谁能帮我解决这个问题?
I found several mistakes in your code, first "return" can be only used at the end of a function. You can put ngram=[] outside the function instead of in the if statement.我在你的代码中发现了几个错误,首先“return”只能用在 function 的末尾。你可以将 ngram=[] 放在 function 之外,而不是放在 if 语句中。 Here is the revised code, hope it can help you.这是修改后的代码,希望对你有帮助。
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.