python - 试图在文件中找到最长的单词 - 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)
解决方案
注意两点——
如果文件不为空,则返回最大长度而不是 n 打印它(与文件为空的情况相比)。
您返回最长单词的长度,而不是单词本身。
请参阅下面的代码,该代码迭代所有单词并找到最长的单词。我将列表转换为设置以提高效率。
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)
推荐阅读
- azure - 如何在 HDInsight 群集中编写用户帐户脚本
- python-3.x - 飞扬的鸟pygame中的管道产卵太快
- python - 在 openpyxl 中使用 add_table() 方法会损坏现有的 excel 文件
- swift - (Swift)如何计算时间(字符串)和单击按钮时间之间的秒数?
- java - 如何在 Spring 中对 @RequestParam 执行验证
- python-3.x - “f = \”作为python中的标题
- spring - 即使未在循环内执行提交,Spring Kafka 也不会再次轮询
- xcode - 可以使用Xcode12的.command时如何让MacApp窗口背景透明或半透明
- c++ - 具有单继承的类的指针转换偏移
- postgresql - PostGIS 使用 epsg 5186 将米转换为度数