だから私は今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'))
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加