gpt4 book ai didi

python - 查找文本文件中最长的单词和最大的数字

转载 作者:行者123 更新时间:2023-12-04 10:45:03 24 4
gpt4 key购买 nike

所以我现在正在学习 python,我真的需要你的帮助。
例如,您确实有包含单词和数字的随机文本文件。
您需要在此文件中找到最长的单词和最大数字。
我设法做到了前半部分,我找到了最长的词:

def longest_word(word):
with open(word, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]
print (("the longest word is :"), longest_word ('text.txt'))

你能帮我完成第二部分吗?如何在文件中找到最大数量?

最佳答案

您可以实现错误处理并尝试将 str 解析为 int: "2"--> 2

def longest_integer(word):
max_int = 0
with open(word, 'r') as infile:
words = infile.read().split()
for word in words:
try:
int_val = int(word)
if int_val > max_int:
max_int = int_val
except:
pass
return max_int
print (("the longest integer is :"), longest_integer ('text.txt'))

关于python - 查找文本文件中最长的单词和最大的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59740970/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com