pbn2xml.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from pprint import pprint
  2. from xml.etree.ElementTree import Element, SubElement, dump, tostring, ElementTree
  3. import xml.dom.minidom
  4. def process_pbn(xml_root):
  5. order_of_suits = ["Spades", "Hearts", "Diamonds", "Clubs"]
  6. with open('hands.pbn', 'r') as f:
  7. for line in f:
  8. if '[Deal ' in line:
  9. # print('{}'.format(line))
  10. # print('{}'.format(line[7]))
  11. print('{}'.format(line[9:-3]))
  12. first_hand = line[7]
  13. assert first_hand in ['N', 'E', 'S', 'W'], \
  14. "Cannot determine first hand. Got {} but expected 'N', 'E', 'S' or 'W'".format(first_hand)
  15. order_of_hands = []
  16. if first_hand == 'N':
  17. order_of_hands = ["North", "East", "South", "West"]
  18. hands = line[9:-3].split(' ')
  19. assert len(hands) == 4, "There are no 4 hands in PBN string {}".format(line[9:-3])
  20. xml_deal = Element("Deal")
  21. dump(xml_deal)
  22. for hand in hands:
  23. i = 0
  24. if '.' in hand:
  25. xml_hand = Element("Hand")
  26. xml_hand.attrib["Position"] = order_of_hands[i]
  27. suits = hand.split('.')
  28. assert len(suits) == 4, "There are no 4 suits in PBN hand {}".format(suits)
  29. j = 0
  30. for suit in suits:
  31. xml_hand.attrib[order_of_suits[j]] = suit
  32. j += 1
  33. dump(xml_hand)
  34. SubElement(xml_deal, xml_hand)
  35. # dump(xml_deal)
  36. i += 1
  37. SubElement(xml_root, xml_deal)
  38. if __name__ == '__main__':
  39. xml_dealsets = Element("DealSets")
  40. process_pbn(xml_dealsets)
  41. dump(xml_dealsets)