【问题标题】:Python - Finding the longest word in a text file errorPython - 在文本文件错误中查找最长的单词
【发布时间】:2021-10-31 16:57:41
【问题描述】:

我正在尝试在文本文件中查找最长的单词,但它一直在说: ValueError: max() arg is an empty sequence

def find_longest_word(filename):
    with open(filename,'r+') as f:
        words = f.read().split()
        max_len_word = max(words,key=len)   
        print('maximum length word in file :',max_len_word)
        print('length is : ',max_len_word)
  
print(find_longest_word('data1.txt'))

我做错了什么?

【问题讨论】:

  • 这是因为words 是一个空序列我猜...
  • 顺便说一句,max_len = len(max_len_word) 无需再次迭代。

标签: python text txt


【解决方案1】:

我已经测试了函数内部的代码,它可以工作,但没有函数声明。

我看到您的代码在第 2 行缺少缩进。此外,您想从函数打印返回值,但您的函数不返回任何内容。所以也许你的代码应该是这样的。

def find_longest_word(filename):
    with open(filename,'r+') as f:
        words = f.read().split()
        max_len_word = max(words,key=len)
        max_len = len(max(words,key=len))       
        return max_len_word, max_len

而且函数的用法应该是这样的。

word, length = find_longest_word('data1.txt')
print("max length word in file: ", word)
print("length is: ", length)

【讨论】:

  • 已回答,但感谢您的贡献!
【解决方案2】:

这应该适合你:

from functools import reduce

def find_longest_word(filename):
    f = open(filename, "r")
    s = [y for x in f.readlines() for y in x.split()]
    longest_word = reduce(lambda x, y: y if len(x) < len(y) else x, s, "")
    print("The longest word is", longest_word, "and it is", len(longest_word),"characters long")

    return longest_word
  
print(find_longest_word('input.txt'))

【讨论】:

  • 表示reduce没有定义。
  • 检查更新的答案。您必须从 functools 导入
猜你喜欢
  • 2013-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-28
  • 1970-01-01
  • 2022-01-03
  • 2015-12-11
  • 1970-01-01
相关资源
最近更新 更多