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

37次阅读
没有评论

共计 637 个字符,预计需要花费 2 分钟才能阅读完成。

要找到一串文本中最长的单词长度,可以使用以下的 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。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-16发表,共计637字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)