首页 > 解决方案 > 试图在文件中找到最长的单词 - Python

问题描述

我目前正在尝试编写一个函数来查找文件中最长的单词,然后打印它所在的行和单词。我不确定出了什么问题,但我只是传递一个空文件。到目前为止,这是我的代码:

def longest_word(file_name):
    data_file = open(file_name, "r")
    lst = [word.rstrip("\n")for word in data_file]
    if len(lst) == 0:
        print('its empty')
    else:
        return (max(len(word) for word in lst)+1)

标签: python

解决方案


注意两点——

  1. 如果文件不为空,则返回最大长度而不是 n 打印它(与文件为空的情况相比)。

  2. 您返回最长单词的长度,而不是单词本身。

  3. 请参阅下面的代码,该代码迭代所有单词并找到最长的单词。我将列表转换为设置以提高效率。

    def longest_word(file_name):
        data_file = open(file_name, "r")
        lst = [word.rstrip("\n")for word in data_file]
        if len(lst) == 0:
            print('its empty')
        else:
            max_length = -1
            max_word = None
            for word in last:
                if len(word) > max_length:
                   max_length = len(word)
                   max_word = word
            print(max_word)
    

推荐阅读