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

标签 python text-files

这是我的代码:

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']

关于python - 搜索文本文件 - 高分(使用 Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48362221/

相关文章:

python - 删除所有满足正则表达式条件的行

python - 如何在python中迭代列表的元组列表,并一一获取所有元素?

python - Python 中具有特定方差的随机数

c++ - 如何从文本文件中取出标记并将其放入二维矩阵中?

Python读取带有换行符和段落分隔元素的文本文件

python - 如何使用 Python/Pâté 在 Kate 中创建新文件 View ?

python - 如何反转Python中PriorityQueue的顺序?

c# - 如果不存在则创建一个 .txt 文件,如果确实存在则追加一个新行

java - 在 Java 中,如何写入最近读取的文件?

php - 如何打开文本文件并使用 php 以追加方式写入文件?