Python 返回句子中最长的单词

Python 返回句子中最长的单词,python,Python,我想找出句子中最长的单词,以便在测试时 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

我想找出句子中最长的单词,以便在测试时

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)
它不工作,错误消息是“未定义名称语句”。它没有检查过一个句子吗?

您可以使用“max”:


调用该函数时,为“句子”参数提供主句中的单词列表

例如:

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\u 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

我对你的代码做了一些更改。首先,我将单词分配给
最长的单词,而不是长度,因此当您使用assert方法时,您不会将单词“句子”与他的长度进行比较。下面的代码应该有效:

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'

它在哪一行给出了错误?m是第二行吗?
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'