Searching Text Files - High Scores (using Python)

131
January 21, 2018, at 07:39 AM

Here is my code:

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

This is what the text file looks like:

mary|4
john|5
lisa|3

I want to read from the file this file and find the highest score. Perhaps using the max function? I'm not sure how to even go about this though. Is there a way to search a file like you can search a list?

Answer 1

Pandas has a clean interface for this kind of task:

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

You can simply use pandas to read your file as a dataFrame and then convert it to an array or list:

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

You didn't need to use a csvwriter for a simple txt file.

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])
Answer 4

I am doing it only using pure python

First you need to load the file

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

You need so keep the best username and his score

best_username = ""
best_score = -1

Now go through each line

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

The result is in best_username. This gets you first user with the highest score

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

returns john

EDIT:

there may be blank line at the end of file, to ignore it use:

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
EDIT 2:

You need to convert score to int, should have tested my code

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
READ ALSO
Square Connect API V2 ListCustomers not returning all customers

Square Connect API V2 ListCustomers not returning all customers

I'm working with the Square Connect API V2 trying to do something very simple: list all my customersFrom my Square dashboard I can see I have ~8k customers, but when using the ListCustomers endpoint, I only receive 151

123
What is effect of the migration scheme on a database?

What is effect of the migration scheme on a database?

I am supporting a software that uses SQLAlchemy database on PythonI need to add the column to this database

144
Twitter user_timeline not returning enough tweets

Twitter user_timeline not returning enough tweets

I'm currently using the GET statuses/user_timeline twitter API in python to retrieve tweets, It says in the docs This method can only return up to 3,200 of a user’s most recent Tweets however when i run it, it only returns 100-150

187
Canvas background of page doesn't recognize hover

Canvas background of page doesn't recognize hover

I have the canvas as the background to my pageI created an interaction with the mouse - but it doesn't recognize it because there is content above

138