#!/usr/bin/env python from optparse import OptionParser TYPES = ( 'artifact', 'creature', 'enchantment', 'instant', 'land', 'plane', 'planeswalker', 'sorcery', 'tribal', 'vanguard') SUPERTYPES = ( 'basic', 'snow', 'legendary', 'world') class Card(object): """Container. The card text and its parsed representation is in here. """ def __init__(self): self.name = None # *all* cards have names. self.text = [] # *all* cards have (oracle) text. self.cost = None self.types = [] self.subtypes = [] #self.supertype = None self.textbox = [] self.power = None self.toughness = None def parse(self): self.name = self.text[0] if self.text[1].split()[0] in TYPES + SUPERTYPES: self.parse_uncosted_card() else: self.parse_costed_card() def parse_uncosted_card(self): """Parses an uncosted card, like a land or a suspend-only """ pass def parse_costed_card(self): """Parses a card with a converted mana cost. """ self.cost = self.text[1] self.parse_typeline(self.text[2]) self.textbox = self.text[3:] if 'Creature' in self.types: self.creature_processing() def parse_typeline(self, typeline): if " - " in typeline: typstr, subtypstr = typeline.split(' - ') else: typstr = typeline.strip().strip() subtypstr = "" self.types = typstr.split(' ') self.subtypes = subtypstr.split(' ') def creature_processing(self): ptline = self.textbox.pop(0) p, t = ptline.split('/') # * will be None. Power on a noncreature card is meaningless. try: self.power = int(p) except ValueError: pass try: self.toughness = int(t) except ValueError: pass class Scanner(object): """Scans cards for features.""" def __init__(self): self.sets = {} def scan_set(self, set_file): """Scans a set file. """ setname = set_file.replace('oracle-', '').replace('.txt', '') self.sets[setname] = [] f = open(set_file, 'r') while True: c = Card() # Get the next card's text... l = None while True: l = f.readline() if l in ('\n', ''): break c.text.append(l.strip()) if l == "": # Dropped off the end of the file, obv. break # Parse it, stick it in this set, then move on. c.parse() self.sets[setname].append(c) print "Processed", c.name print setname, "has", len(self.sets[setname]), "cards" if __name__ == "__main__": parser = OptionParser() (options, args) = parser.parse_args() s = Scanner() for set_file in args: s.scan_set(set_file)