Skip to main content
 首页 » 编程设计

python之搜索文本文件之高分(使用 Python)

2025年05月04日21birdshome

这是我的代码:

results = [[username, score]] 
 
if (topic == 'history') and (difficulty == 'easy'): 
    with open("hisEasyR.txt", "a") as hisEasyRFile: 
        writer = csv.writer(hisEasyRFile, delimiter='|') 
        writer.writerows(results) 

这是文本文件的样子:

mary|4 
john|5 
lisa|3 

我想从文件中读取这个文件并找到最高分。也许使用 max 函数?不过,我不确定该怎么做。有没有一种方法可以像搜索列表一样搜索文件?

请您参考如下方法:

Pandas 为此类任务提供了一个干净的界面:

import pandas as pd 
 
df = pd.read_csv(filepath, delimiter='|', header=None, names=['username', 'score']) 
 
highest_score = df['score'].max() 
highest_score_username = df.loc[df['score'] == highest_score, 'username']