from pprint import pprint from xml.etree.ElementTree import Element, SubElement, dump, tostring, ElementTree import xml.dom.minidom def process_pbn(xml_root): order_of_suits = ["Spades", "Hearts", "Diamonds", "Clubs"] with open('hands.pbn', 'r') as f: for line in f: if '[Deal ' in line: # print('{}'.format(line)) # print('{}'.format(line[7])) print('{}'.format(line[9:-3])) first_hand = line[7] assert first_hand in ['N', 'E', 'S', 'W'], \ "Cannot determine first hand. Got {} but expected 'N', 'E', 'S' or 'W'".format(first_hand) order_of_hands = [] if first_hand == 'N': order_of_hands = ["North", "East", "South", "West"] hands = line[9:-3].split(' ') assert len(hands) == 4, "There are no 4 hands in PBN string {}".format(line[9:-3]) xml_deal = Element("Deal") dump(xml_deal) for hand in hands: i = 0 if '.' in hand: xml_hand = Element("Hand") xml_hand.attrib["Position"] = order_of_hands[i] suits = hand.split('.') assert len(suits) == 4, "There are no 4 suits in PBN hand {}".format(suits) j = 0 for suit in suits: xml_hand.attrib[order_of_suits[j]] = suit j += 1 dump(xml_hand) SubElement(xml_deal, xml_hand) # dump(xml_deal) i += 1 SubElement(xml_root, xml_deal) if __name__ == '__main__': xml_dealsets = Element("DealSets") process_pbn(xml_dealsets) dump(xml_dealsets)