Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJames N
17,864 PointsI'm working on a seperate project and i need help with regular expressions:
I'm working on a seperate project not mentioned in a Treehouse course.
It's an application which will allow me to organize my collection of games.
I can view info about the game (will just print the __str__
of the game class),
I can sort games by an attribute,
and i can add a new game to the list.
I'm trying to make it so that i have the ability to load games that were previously saved, but i can't think of what i'd type for the regular expression!
thanks, James.
import os
import re
import time
class Game():
"""My custom class created in which to have a database for my video games.
This class has 7 attributes:
The game's name
The game's platform (eg. Xbox one, ps4)
The game's ESRB rating (eg. E, T, M)
The game's genre (eg. FPS, RTS, MMORPG)
My personal rating for the game (/5 stars)
The type of game (whether it's downloaded on a hard drive or stored on a disc)
and, the developer of the game"""
def __init__(self, Name, Platform, ESRB, Genre, Personal, Type, Dev):
self.Name = Name
self.Platform = Platform
self.ESRB = ESRB
self.Genre = Genre
self.Personal = Personal
self.Type = Type
self.Dev = Dev
def __str__(self):
return "The game {} is for {} and is a {} game. It is rated {} by the ESRB and I give it {}/5 Stars. It is a {} game made by {}.".format(self.Name, self.Platform, self.Genre, self.ESRB, self.Personal, self.Type, self.Dev)
#Setters
def setName(self, name):
self.Name = name
def setPlatform(self, plat):
self.Platform = plat
def setESRB(self, esrb):
self.ESRB = esrb
def setGenre(self, genre):
self.Genre = genre
def setPersonal(self, pers):
self.Personal = pers
def setType(self, type):
self.Type = type
def setDev(self, dev):
self.Dev = dev
#Game Class:
# Name
# Platform
# ESRB rating (age)
# Genre
# Personal rating (good / bad)
# Type (Download, Disc, etc.)
# Developer
#Name, Platform, ESRB, Genre, Personal, Type, Dev
GameList = [ #My current list of test games; will be empty in final version.
Game("253478573489578957340985","2","6","2","3","4","4"),
Game("2645645645","2","6","2","3","4","4"),
Game("25634563456345645634564536454563456","2","6","2","3","4","4"),
Game("23456","2","6","2","3","4","4"),
Game("265463456456453656","2","6","2","3","4","4"),
Game("265476543763456","2","6","2","3","4","4")
]
def InvalidInput():
ClearScreen()
print("\n Invalid input.")
MainUI()
def DelayPrint(text):
count = 5
while count > 0:
ClearScreen()
print("\n")
print("\033[1;37;41m" + str(text) + "\033[1;37;40m")
print("----------------------------------------")
print("You can input again in {} seconds...".format(count))
time.sleep(1)
count -= 1
def InfoView():
print("\nType which game you would like info about")
gameinput = input(">> ").lower()
ClearScreen()
for game in GameList:
if game.Name.lower() == gameinput:
print("\n\n")
DelayPrint(game)
ClearScreen()
break
else:
continue
else:
InvalidInput()
def ViewList():
color = 0
for game in GameList:
if color == 1:
print("\033[1;37;41m" + game.Name + "\033[1;37;40m")
color -= 1
else:
print(game.Name)
color += 1
def SortView():
print("What do you want to sort by?")
print("You can currently sort by:\n'platform': Platform (what system the game is for),\n'esrb': ESRB rating (whether it's rated Teen, Mature, etc.)\n'genre': Genre,\n'james': James' personal rating, (out of 5 stars, .5's are allowed, please only type a number)\n'publisher': The publisher of the game")
sortInput = input(">> ").lower()
if sortInput == "platform" or sortInput == "esrb" or sortInput == "genre" or sortInput == "james" or sortInput == "publisher":
if sortInput == "james" or sortInput == "esrb":
print("\nPlease enter {}".format(sortInput + " rating" ))
else:
print("\nPlease enter {}".format(sortInput))
query = input(">> ")
ClearScreen()
if sortInput == "james" or sortInput == "esrb":
print("\nHere are the \033[1;31;40m{}\033[1;37;40m games sorted by \033[1;31;40m{}\033[1;37;40m:".format(query, sortInput + " rating"))
else:
print("\nHere are the \033[1;31;40m{}\033[1;37;40m games sorted by \033[1;31;40m{}\033[1;37;40m:".format(query, sortInput))
if sortInput == "platform":
print("----------------------------------------")
color = 0
for game in GameList:
if game.Platform.lower() == query.lower():
if color == 1:
print("\033[1;37;41m" + game.Name + "\033[1;37;40m")
color -= 1
else:
print(game.Name)
color += 1
else:
continue
elif sortInput == "esrb":
print("----------------------------------------")
color = 0
for game in GameList:
if game.ESRB.lower() == query.lower():
if color == 1:
print("\033[1;37;41m" + game.Name + "\033[1;37;40m")
color -= 1
else:
print(game.Name)
color += 1
else:
continue
elif sortInput == "genre":
print("----------------------------------------")
color = 0
for game in GameList:
if game.Genre.lower() == query.lower():
if color == 1:
print("\033[1;37;41m" + game.Name + "\033[1;37;40m")
color -= 1
else:
print(game.Name)
color += 1
else:
continue
elif sortInput == "james":
print("----------------------------------------")
color = 0
for game in GameList:
if game.Personal.lower() == query.lower():
if color == 1:
print("\033[1;37;41m" + game.Name + "\033[1;37;40m")
color -= 1
else:
print(game.Name)
color += 1
else:
continue
else:
print("----------------------------------------")
color = 0
for game in GameList:
if game.Dev.lower() == query.lower():
if color == 1:
print("\033[1;37;41m" + game.Name + "\033[1;37;40m")
color -= 1
else:
print(game.Name)
color += 1
else:
continue
time.sleep(5)
else:
InvalidInput()
ClearScreen()
def ClearScreen():
if os.name == "nt":
os.system("cls")
else:
os.system("clear")
def MainUI():
while True:
print("----------------------------------------")
ViewList()
print("----------------------------------------")
print("These are the games that you currently own.")
PromptForAction()
def SaveNewGame(): #The method that saves games. will save to a file called "games.txt"
ClearScreen()
print("")
newGameToSave = Game(None,None,None,None,None,None,None)
print("Please enter the Game's name:")
name = input(">> ")
newGameToSave.setName(name)
print("Please enter the Game's platform:")
plat = input(">> ")
newGameToSave.setPlatform(plat)
print("Please enter the Game's ESRB rating:")
esrb = input(">> ")
newGameToSave.setESRB(esrb)
print("Please enter the Game's genre:")
genre = input(">> ")
newGameToSave.setGenre(genre)
print("Please enter the your opinion on this game; out of 5 stars, and .5's are allowed. (eg. 3.5, 5, 0.5):")
rating = input(">> ") + "/5 Stars"
newGameToSave.setPersonal(rating)
print("Please enter the type of media it is stored on (eg. cartridge, disc, downloadable):")
type = input(">> ")
newGameToSave.setType(type)
print("Please enter the Game's publisher:")
pub = input(">> ")
newGameToSave.setDev(pub)
DelayPrint(newGameToSave)
print("")
if input("Add your new game? [Y/n] ").lower() != "n":
ClearScreen()
print("")
print("Saving.")
time.sleep(0.5)
ClearScreen()
print("")
print("Saving..")
time.sleep(0.5)
ClearScreen()
print("")
print("Saving...")
time.sleep(0.5)
ClearScreen()
print("")
print("Saving.")
time.sleep(0.5)
ClearScreen()
print("")
print("Saving..")
time.sleep(0.5)
ClearScreen()
print("")
print("Saving...")
time.sleep(0.5)
ClearScreen()
print("")
print("Saving.")
time.sleep(0.5)
ClearScreen()
print("")
print("Saving..")
time.sleep(0.5)
ClearScreen()
print("")
print("Saving...")
time.sleep(0.5)
GameList.append(newGameToSave)
with open("games.txt", "w") as out_file:
for i in range(len(GameList)):
out_string = ""
out_string += str(GameList[i])
out_string += "\n" + str(GameList[i])
out_file.write(out_string)
DelayPrint("The game {} has been added succesfully!".format(newGameToSave.Name))
ClearScreen()
else:
ClearScreen()
MainUI()
def PromptForAction():
print("\n")
print("What do you wish to do?")
print("----------------------------------------\ntype 'quit' to quit,")
print("type 'info' to view info about a game,")
print("type 'new' to add a new game to the list,")
print("type 'sort' to view games sorted by a category of your choice, ")
print("or, if the screen gets messy, type 'clear' to fix that!\n----------------------------------------")
action = input(">> ").lower()
if action == "quit":
#The massive print statement below prints an ASCII art troll face. ;-)
print(" .....'',;;::cccllllllllllllcccc:::;;,,,''...'',,'..\n ..';cldkO00KXNNNNXXXKK000OOkkkkkxxxxxddoooddddddxxxxkkkkOO0XXKx:.\n .':ok0KXXXNXK0kxolc:;;,,,,,,,,,,,;;,,,''''''',,''.. .'lOXKd'\n .,lx00Oxl:,'............''''''................... ...,;;'. .oKXd.\n .ckKKkc'...'',:::;,'.........'',;;::::;,'..........'',;;;,'.. .';;'. 'kNKc.\n .:kXXk:. .. .................. .............,:c:'...;:'. .dNNx.\n :0NKd, .....''',,,,''.. ',...........',,,'',,::,...,,. .dNNx.\n .xXd. .:;'.. ..,' .;,. ...,,'';;'. ... .oNNo\n .0K. .;. ;' '; .'...'. .oXX:\n .oNO. . ,. . ..',::ccc:;,.. .. lXX:\n .dNX: ...... ;. 'cxOKK0OXWWWWWWWNX0kc. :KXd.\n .l0N0; ;d0KKKKKXK0ko:... .l0X0xc,...lXWWWWWWWWKO0Kx' ,ONKo.\n .lKNKl...'......'. .dXWN0kkk0NWWWWWN0o. :KN0;. .,cokXWWNNNNWNKkxONK: .,:c:. .';;;;:lk0XXx;\n :KN0l';ll:'. .,:lodxxkO00KXNWWWX000k. oXNx;:okKX0kdl:::;'',;coxkkd, ...'. ...'''.......',:lxKO:.\n oNNk,;c,'',. ...;xNNOc,. ,d0X0xc,. .dOd, ..;dOKXK00000Ox:. ..''dKO,\n'KW0,:,.,:..,oxkkkdl;'. 'KK' .. .dXX0o:'....,:oOXNN0d;.'. ..,lOKd. .. ;KXl.\n;XNd,; ;. l00kxoooxKXKx:..ld: ;KK' .:dkO000000Okxl;. c0; :KK; . ;XXc\n'XXdc. :. .. '' 'kNNNKKKk, .,dKNO. .... .'c0NO' :X0. ,. xN0.\n.kNOc' ,. .00. ..''... .l0X0d;. 'dOkxo;... .;okKXK0KNXx;. .0X: ,. lNX'\n ,KKdl .c, .dNK, .;xXWKc. .;:coOXO,,'....... .,lx0XXOo;...oNWNXKk:.'KX; ' dNX.\n :XXkc'.... .dNWXl .';l0NXNKl. ,lxkkkxo' .cK0. ..;lx0XNX0xc. ,0Nx'.','.kXo ., ,KNx.\n cXXd,,;:, .oXWNNKo' .'.. .'.'dKk; .cooollox;.xXXl ..,cdOKXXX00NXc. 'oKWK' ;k: .l. ,0Nk.\n cXNx. . ,KWX0NNNXOl'. .o0Ooldk; .:c;.':lxOKKK0xo:,.. ;XX: .,lOXWWXd. . .':,.lKXd.\n lXNo cXWWWXooNWNXKko;'.. .lk0x; ...,:ldk0KXNNOo:,.. ,OWNOxO0KXXNWNO, ....'l0Xk,\n .dNK. oNWWNo.cXK;;oOXNNXK0kxdolllllooooddxk00KKKK0kdoc:c0No .'ckXWWWNXkc,;kNKl. .,kXXk,\n 'KXc .dNWWX;.xNk. .kNO::lodxkOXWN0OkxdlcxNKl,.. oN0'..,:ox0XNWWNNWXo. ,ONO' .o0Xk;\n .ONo oNWWN0xXWK, .oNKc .ONx. ;X0. .:XNKKNNWWWWNKkl;kNk. .cKXo. .ON0;\n .xNd cNWWWWWWWWKOkKNXxl:,'...;0Xo'.....'lXK;...',:lxk0KNWWWWNNKOd:.. lXKclON0: .xNk.\n .dXd ;XWWWWWWWWWWWWWWWWWWNNNNNWWNNNNNNNNNWWNNNNNNWWWWWNXKNNk;.. .dNWWXd. cXO.\n .xXo .ONWNWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWNNK0ko:'..OXo 'l0NXx, :KK,\n .OXc :XNk0NWXKNWWWWWWWWWWWWWWWWWWWWWNNNX00NNx:'.. lXKc. 'lONN0l. .oXK:\n .KX; .dNKoON0;lXNkcld0NXo::cd0NNO:;,,'.. .0Xc lXXo..'l0NNKd,. .c0Nk,\n :XK. .xNX0NKc.cXXl ;KXl .dN0. .0No .xNXOKNXOo,. .l0Xk;.\n .dXk. .lKWN0d::OWK; lXXc .OX: .ONx. . .,cdk0XNXOd;. .\'\'\'....;c:'..;xKXx,\n .0No .:dOKNNNWNKOxkXWXo:,,;ONk;,,,,,;c0NXOxxkO0XXNXKOdc,. ..;::,...;lol;..:xKXOl.\n ,XX: ..';cldxkOO0KKKXXXXXXXXXXKKKKK00Okxdol:;'.. .';::,..':llc,..'lkKXkc.\n :NX' . '' .................. .,;:;,',;ccc;'..'lkKX0d;.\n lNK. .; ,lc,. ................ ..,,;;;;;;:::,....,lkKX0d:.\n .oN0. .'. .;ccc;,'.... ....'',;;;;;;;;;;'.. .;oOXX0d:.\n .dN0. .;;,.. .... ..''''''''.... .:dOKKko;.\n lNK' ..,;::;;,'......................... .;d0X0kc'.\n .xXO' .;oOK0x:.\n .cKKo. .,:oxkkkxk0K0xc'.\n .oKKkc,. .';cok0XNNNX0Oxoc,.\n .;d0XX0kdlc:;,,,',,,;;:clodkO0KK0Okdl:,'..\n .,coxO0KXXXXXXXKK0OOxdoc:,..")
time.sleep(5)
ClearScreen()
exit()
elif action == "info":
InfoView()
elif action == "clear":
ClearScreen()
elif action == "sort":
#WIP
SortView()
elif action == "new":
#WIP
SaveNewGame()
else:
InvalidInput()
def LoadFile(): #Here it is! the LoadFile method:
try:
readMe = open("games.txt","r").readlines()
print(readMe)
for line in readMe:
newGameToLoad = Game(None, None, None, None, None, None, None)
name = re.compile("") #Can't think of what to put for regex :-(
except FileNotFoundError:
print("No game data detected!\nYou now need to manually add games using the 'new' command.\n. .\n----\n")
LoadFile()
time.sleep(5)
ClearScreen()
MainUI()
1 Answer
Steven Parker
230,853 PointsThe file format made this a bit complicated.
You might consider storing the games in a simpler format, perhaps CSV (like the test games list). But for now, this seems to parse the strings and load the games:
def LoadFile(): #Here it is! the LoadFile method:
try:
readMe = open("games.txt","r").readlines()
for line in readMe:
game = re.search(r'''
The\ game\ (?P<Name>.*)\ is\ for\ (?P<Platform>.*)\ and\ is\ a\ (?P<Genre>.*)\ game.\s+
It\ is\ rated\ (?P<ESRB>.*)\ by\ the\ ESRB\ and\ I\ give\ it\ (?P<Personal>.*)/5\ Stars.\s+
It\ is\ a\ (?P<Type>.*)\ game\ made\ by\ (?P<Dev>.*)\.
''', line, re.X)
newGameToLoad = Game(**game.groupdict())
GameList.append(newGameToLoad)
except FileNotFoundError:
print("No game data detected!\nYou now need to manually add games using the 'new' command.\n. .\n----\n")
While I was at it, I broke the "face" up into multiple lines to eliminate the HUGE long line and also so you can "see" it:
#The massive print statement below prints an ASCII art troll face. ;-)
print(" .....'',;;::cccllllllllllllcccc:::;;,,,''...'',,'..\n"
" ..';cldkO00KXNNNNXXXKK000OOkkkkkxxxxxddoooddddddxxxxkkkkOO0XXKx:.\n"
" .':ok0KXXXNXK0kxolc:;;,,,,,,,,,,,;;,,,''''''',,''.. .'lOXKd'\n"
" .,lx00Oxl:,'............''''''................... ...,;;'. .oKXd.\n"
" .ckKKkc'...'',:::;,'.........'',;;::::;,'..........'',;;;,'.. .';;'. 'kNKc.\n"
" .:kXXk:. .. .................. .............,:c:'...;:'. .dNNx.\n"
" :0NKd, .....''',,,,''.. ',...........',,,'',,::,...,,. .dNNx.\n"
" .xXd. .:;'.. ..,' .;,. ...,,'';;'. ... .oNNo\n"
" .0K. .;. ;' '; .'...'. .oXX:\n"
" .oNO. . ,. . ..',::ccc:;,.. .. lXX:\n"
" .dNX: ...... ;. 'cxOKK0OXWWWWWWWNX0kc. :KXd.\n"
" .l0N0; ;d0KKKKKXK0ko:... .l0X0xc,...lXWWWWWWWWKO0Kx' ,ONKo.\n"
" .lKNKl...'......'. .dXWN0kkk0NWWWWWN0o. :KN0;. .,cokXWWNNNNWNKkxONK: .,:c:. .';;;;:lk0XXx;\n"
" :KN0l';ll:'. .,:lodxxkO00KXNWWWX000k. oXNx;:okKX0kdl:::;'',;coxkkd, ...'. ...'''.......',:lxKO:.\n"
" oNNk,;c,'',. ...;xNNOc,. ,d0X0xc,. .dOd, ..;dOKXK00000Ox:. ..''dKO,\n"
"'KW0,:,.,:..,oxkkkdl;'. 'KK' .. .dXX0o:'....,:oOXNN0d;.'. ..,lOKd. .. ;KXl.\n"
";XNd,; ;. l00kxoooxKXKx:..ld: ;KK' .:dkO000000Okxl;. c0; :KK; . ;XXc\n"
"'XXdc. :. .. '' 'kNNNKKKk, .,dKNO. .... .'c0NO' :X0. ,. xN0.\n"
".kNOc' ,. .00. ..''... .l0X0d;. 'dOkxo;... .;okKXK0KNXx;. .0X: ,. lNX'\n"
" ,KKdl .c, .dNK, .;xXWKc. .;:coOXO,,'....... .,lx0XXOo;...oNWNXKk:.'KX; ' dNX.\n"
" :XXkc'.... .dNWXl .';l0NXNKl. ,lxkkkxo' .cK0. ..;lx0XNX0xc. ,0Nx'.','.kXo ., ,KNx.\n"
" cXXd,,;:, .oXWNNKo' .'.. .'.'dKk; .cooollox;.xXXl ..,cdOKXXX00NXc. 'oKWK' ;k: .l. ,0Nk.\n"
" cXNx. . ,KWX0NNNXOl'. .o0Ooldk; .:c;.':lxOKKK0xo:,.. ;XX: .,lOXWWXd. . .':,.lKXd.\n"
" lXNo cXWWWXooNWNXKko;'.. .lk0x; ...,:ldk0KXNNOo:,.. ,OWNOxO0KXXNWNO, ....'l0Xk,\n"
" .dNK. oNWWNo.cXK;;oOXNNXK0kxdolllllooooddxk00KKKK0kdoc:c0No .'ckXWWWNXkc,;kNKl. .,kXXk,\n"
" 'KXc .dNWWX;.xNk. .kNO::lodxkOXWN0OkxdlcxNKl,.. oN0'..,:ox0XNWWNNWXo. ,ONO' .o0Xk;\n"
" .ONo oNWWN0xXWK, .oNKc .ONx. ;X0. .:XNKKNNWWWWNKkl;kNk. .cKXo. .ON0;\n"
" .xNd cNWWWWWWWWKOkKNXxl:,'...;0Xo'.....'lXK;...',:lxk0KNWWWWNNKOd:.. lXKclON0: .xNk.\n"
" .dXd ;XWWWWWWWWWWWWWWWWWWNNNNNWWNNNNNNNNNWWNNNNNNWWWWWNXKNNk;.. .dNWWXd. cXO.\n"
" .xXo .ONWNWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWNNK0ko:'..OXo 'l0NXx, :KK,\n"
" .OXc :XNk0NWXKNWWWWWWWWWWWWWWWWWWWWWNNNX00NNx:'.. lXKc. 'lONN0l. .oXK:\n"
" .KX; .dNKoON0;lXNkcld0NXo::cd0NNO:;,,'.. .0Xc lXXo..'l0NNKd,. .c0Nk,\n"
" :XK. .xNX0NKc.cXXl ;KXl .dN0. .0No .xNXOKNXOo,. .l0Xk;.\n"
" .dXk. .lKWN0d::OWK; lXXc .OX: .ONx. . .,cdk0XNXOd;. .\'\'\'....;c:'..;xKXx,\n"
" .0No .:dOKNNNWNKOxkXWXo:,,;ONk;,,,,,;c0NXOxxkO0XXNXKOdc,. ..;::,...;lol;..:xKXOl.\n"
" ,XX: ..';cldxkOO0KKKXXXXXXXXXXKKKKK00Okxdol:;'.. .';::,..':llc,..'lkKXkc.\n"
" :NX' . '' .................. .,;:;,',;ccc;'..'lkKX0d;.\n"
" lNK. .; ,lc,. ................ ..,,;;;;;;:::,....,lkKX0d:.\n"
" .oN0. .'. .;ccc;,'.... ....'',;;;;;;;;;;'.. .;oOXX0d:.\n"
" .dN0. .;;,.. .... ..''''''''.... .:dOKKko;.\n"
" lNK' ..,;::;;,'......................... .;d0X0kc'.\n"
" .xXO' .;oOK0x:.\n"
" .cKKo. .,:oxkkkxk0K0xc'.\n"
" .oKKkc,. .';cok0XNNNX0Oxoc,.\n"
" .;d0XX0kdlc:;,,,',,,;;:clodkO0KK0Okdl:,'..\n"
" .,coxO0KXXXXXXXKK0OOxdoc:,..")
James N
17,864 PointsJames N
17,864 PointsThanks! Ill get to testing the new code. you didn't have to break the acsii face into multiple lines, and the face didn't appear correctly on the computer i planned to test this on. but thanks anyway! Thanks for the help!
Edit: i watched a video on how to save, and the guy who did it did save it in
.CSV
. what exactly does csv do differently? I thought it would be better to do.txt
just because then the user could actually read the file.Another Edit: I'm getting an AttributeError:
Last Edit: never mind the error, the only reason it wasn't working was because my data was screwed up somehow. after erasing it, it worked perfectly!
Steven Parker
230,853 PointsSteven Parker
230,853 PointsCSV is a readable text format.
But instead of complete sentences it would just show the data items separated by commas — much easier to separate in the program!