I need to extract data from lines of a text file. The data is name and scoring information formatted like this:
Shyvana - 12/4/5 - Loss - 2012-11-22
Fizz - 12/4/5 - Win - 2012-11-22
Miss Fortune - 12/4/3 - Win - 2012-11-22
This file is generated by another part of my little python program where I ask the user for the name, lookup the name they enter to ensure it’s valid from a list of names, and then ask for kills, deaths, assists, and whether they won or lost. Then I ask for confirmation and write that data to the file on a new line, and append the date at the end like that. The code that prepares that data:
data = "%s - %s/%s/%s - %s - %s\n" % (
champname, kills, deaths, assists, winloss, timestamp)
Basically I want to read that data back in another part of the program and display it to the user and do calculations with it like averages over time for a particular name.
I’m new to python and and I’m not very experienced with programming in general so most of the string splitting and formatting examples I find are just too cryptic for me to understand how to adapt to quite what I need here, could anyone help? I could format the written data differently so token finding would be simpler, but I want it to be simple directly in the file.
The following will read everything into a dictionary keyed by player name. The value associated with each player is itself a dictionary acting as a record with named fields associated with the items converted to a format suitable for further processing.
Output:
Alternatively, rather than holding most of the data in dictionaries, which can make nested-field access a little awkward —
info[player]['stats']['kills']— you could instead use a little more advanced “generic” class to hold them, which will let you writeinfo2[player].stats.killsinstead.To illustrate, here’s almost the same thing using a class I’ve named
Structbecause it’s somewhat like the C language’sstructdata type:Output: