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

时间:2018-01-20 23:38:32

标签: 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函数?我不知道怎么回事。有没有办法像搜索列表那样搜索文件?

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

我只使用纯python

首先你需要加载文件

data = ""
with open(filename, "r") as f:
    data = f.read()

您需要保留最佳用户名和分数

best_username = ""
best_score = -1

现在浏览每一行

for line in data.split("\n"):
    username, score = line.split("|")  # reads user and his score from line
    if score > best_score:  # best user we encounterd so far
        best_username = username
        best_score = score

结果在best_username中。这将使您获得评分最高的第一位用户

mary|4
john|5
lisa|3
dana|5

返回约翰

编辑:

文件末尾可能有空行,忽略它使用:

for line in data.split("\n"):
    if "|" not in line:  # skips invalid lines
        continue
    username, score = line.split("|")  # reads user and his score from line
    if score > best_score:  # best user we encounterd so far
        best_username = username
        best_score = score

编辑2:

你需要将得分转换为int,应该测试我的代码

for line in data.split("\n"):
    if "|" not in line:  # skips invalid lines
        continue
    username, score = line.split("|")  # reads user and his score from line
    score = int(score)
    if score > best_score:  # best user we encounterd so far
        best_username = username
        best_score = score

答案 2 :(得分:1)

您可以简单地使用pandas将文件作为dataFrame读取,然后将其转换为数组或列表:

import pandas as pd
df = pd.read_csv('hisEasyR.txt', sep='|', header=None)
print("scores array:", x[1])
print("minimum score:", min(x[1]))

答案 3 :(得分:1)

您不需要将csvwriter用于简单的txt文件。

l = []
with open("hisEasyR.txt", "ab+") as hisEasyRFile:
   for line in hisEasyRFile.read().splitlines():
      if line != '\n':
         l.append([line.split('|')[0], int(line.split('|')[1])])

l.sort(key=lambda element: element[1])
print(l[-1])