首页 > 解决方案 > Python 3: largest number in txt file

问题描述

Thats my code:

def get_latest(file_name):
    max = 0
    with open(file_name) as file:
        for line in file.readlines():            
            num = int(line.split("\t")[2])
            if (max < num):
                max = num
            line=line.split("\t")
            #y=max
            if str(max) in line:
                print(line)

get_latest('game_stat.txt')

That's output:

['Minecraft', '23', '2009', 'Survival game', 'Microsoft\n']
['Terraria', '12', '2011', 'Action-adventure', 'Re-Logic\n']
['Diablo III', '12', '2012', 'RPG', 'Blizzard Entertainment\n']

What should I do to print only line with newest released date?

Txt file looks like this:

Minecraft   23  2009    Survival game   Microsoft
World of Warcraft   14  2004    RPG Blizzard Entertainment
Terraria    12  2011    Action-adventure    Re-Logic
Diablo III  12  2012    RPG Blizzard Entertainment
Half-Life 2 12  2004    First-person shooter    Valve Corporation
Counter-Strike  12.5    1999    First-person shooter    Valve Corporation
The Sims    11.24   2000    Simulation  Electronic Arts
StarCraft   11  1998    Real-time strategy  Blizzard Entertainment
Garry's Mod 10  2006    Sandbox Facepunch Studios
....etc

I can't figure it out. Thanks in advance!

标签: python-3.xmax

解决方案


您需要使用将年份作为整数进行比较的关键函数max来处理所有行。下面,我用来为我解析文件的结构。csv.reader

import csv

def get_latest(file_name):
    with open(file_name, newline='') as file:
        reader = csv.reader(file, dialect='excel-tab')
        return max(reader, key=lambda row: int(row[2]))

print(get_latest('game_stat.txt'))

年份最大的条目将是最近发布的条目。(假设您没有未来游戏的数据。)


推荐阅读