温馨提示×

怎么用python找最长的单词长度

小亿
248
2023-11-07 16:47:23
栏目: 编程语言

要找到一串文本中最长的单词长度,可以使用以下的Python代码实现:

def find_longest_word_length(text):
    words = text.split()  # 将文本分割成单词列表
    longest_word_length = 0

    for word in words:
        if len(word) > longest_word_length:
            longest_word_length = len(word)

    return longest_word_length

text = "This is a sample sentence with some long words"
longest_word_length = find_longest_word_length(text)
print("最长的单词长度为:", longest_word_length)

运行结果:

最长的单词长度为: 8

在这个例子中,我们定义了一个名为find_longest_word_length的函数,该函数接受一个文本参数。函数首先使用split()方法将文本分割成单词列表。然后,使用一个循环遍历每个单词,并使用len()函数计算每个单词的长度。如果某个单词的长度比之前记录的最长单词长度还要长,就更新最长单词长度。最后,函数返回最长单词长度。

在示例中,给定的文本是"This is a sample sentence with some long words",其中最长的单词是"sentence",长度为8。因此,输出结果为8。

0