pbn2xml.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. from datetime import date
  2. # from pprint import pprint
  3. from xml.etree.ElementTree import Element, SubElement, tostring, ElementTree
  4. # from xml.etree.ElementTree import dump
  5. import xml.dom.minidom
  6. def process_pbn(xml_root):
  7. order_of_suits = ["Spades", "Hearts", "Diamonds", "Clubs"]
  8. with open('hands.pbn', 'r') as f_pbn:
  9. for line in f_pbn:
  10. if '[Deal ' in line:
  11. # print('{}'.format(line))
  12. # print('{}'.format(line[7]))
  13. # print('{}'.format(line[9:-3]))
  14. first_hand = line[7]
  15. assert first_hand in ['N', 'E', 'S', 'W'], \
  16. "Cannot determine first hand. Got {} but expected 'N', 'E', 'S' or 'W'".format(first_hand)
  17. order_of_hands = []
  18. if first_hand == 'N':
  19. order_of_hands = ["North", "East", "South", "West"]
  20. hands = line[9:-3].split(' ')
  21. assert len(hands) == 4, "There are no 4 hands in PBN string {}".format(line[9:-3])
  22. xml_deal = SubElement(xml_root, "Deal")
  23. # dump(xml_deal)
  24. i = 0
  25. for hand in hands:
  26. if '.' in hand:
  27. xml_hand = SubElement(xml_deal, "Hand")
  28. xml_hand.attrib["Position"] = order_of_hands[i]
  29. suits = hand.split('.')
  30. assert len(suits) == 4, "There are no 4 suits in PBN hand {}".format(suits)
  31. j = 0
  32. for suit in suits:
  33. xml_hand.attrib[order_of_suits[j]] = suit
  34. j += 1
  35. # dump(xml_hand)
  36. # dump(xml_deal)
  37. i += 1
  38. if __name__ == '__main__':
  39. xml_dealsets = Element("DealSets")
  40. xml_dealset = SubElement(xml_dealsets, "DealSet")
  41. xml_dealset.attrib["ComplexityLevel"] = "1"
  42. xml_dealset.attrib["IBIS-ID"] = "007-Foppe_Hemminga-{}".format(date.today().strftime('%Y%m%d'))
  43. xml_dealset.attrib["VulnerabilityDefault"] = "None"
  44. SubElement(xml_dealset, "Parameters")
  45. process_pbn(xml_dealset)
  46. # dump(xml_dealsets)
  47. xml_tree = ElementTree(xml_dealsets)
  48. dom = xml.dom.minidom.parseString(tostring(xml_dealsets, encoding='utf-8', method='xml'))
  49. # print(dom.toprettyxml().replace('<?xml version="1.0" ?>', '<?xml version=\'1.0\' encoding=\'utf-8\'?>'))
  50. with open("output.xml", 'w') as f_xml:
  51. f_xml.write(dom.toprettyxml().replace('<?xml version="1.0" ?>', '<?xml version=\'1.0\' encoding=\'utf-8\'?>'))
  52. # xml_tree.write("output.xml", encoding="utf-8", xml_declaration=True)