返回句子中最长的单词



我想找到句子中最长的单词,这样在测试时

assert longest_word(sentence.split()) == 'sentence'

我写了这个

def longest_word(sentence):
individual_words = sentence.split()
longest_word = len(individual_words[0])
for i in individual_words:
word_length = len(i)
if word_length > longest_word:
longest_word = word_length
print(longest_word)
return(longest_word)

它不起作用,错误消息是";名称语句未定义";。难道没有一句话可以查透吗?

当您调用该函数时,您会给您的"句子"参数一个主句子中的单词列表。

例如:

sentence = 'This is a string of words sentence'
sentence.split() will return: ['This', 'is', 'a', 'string', 'of', 'words', 'sentence']
But the first line in your function already splits up your string into individual words, so you're confusing python with which data you're giving it and how```

我对您的代码进行了一些更改。首先,我把单词分配给了longest_word,而不是长度,所以当你使用断言方法时,你不会把单词"句子"和他的长度进行比较。下面的代码应该可以工作:

def longest_word(sentence):
individual_words = sentence.split()
longest_word = individual_words[0]
for i in individual_words:
word_length = len(i)
if word_length > len(longest_word):
longest_word = i
print(longest_word)
return(longest_word)

sentence='I want to find the longest word in a sentence so that when tested'
assert longest_word(sentence) == 'sentence'

有一种较短的方法。

例如,在这段代码中,函数longest_word将句子拆分为多个字符串(单词(,我们从中找到其中最长的一个。

sentence = 'This is a string of words namely a sentence'
def longest_word(strings):
return max(strings, key = len)
print(longest_word(sentence.split()))
assert longest_word(sentence.split()) == 'sentence'

输出:

sentence

您可以使用;max":

sentence="Find out longest word"
lst=sentence.split(' ')
max(lst, key=len)

最新更新