| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- import re
- from datetime import date
- # from pprint import pprint
- from xml.etree.ElementTree import Element, SubElement, tostring, ElementTree
- # from xml.etree.ElementTree import dump
- import xml.dom.minidom
- def process_pbn(xml_root):
- order_of_suits = ["Spades", "Hearts", "Diamonds", "Clubs"]
- dict_of_hands = {"N": "North", "E": "East", "S": "South", "W": "West"}
- dealer = ''
- vulnerable = ''
- with open('hands.pbn', 'r') as f_pbn:
- for line in f_pbn:
- if not line.strip():
- dealer = ''
- vulnerable = ''
- if '[Dealer' in line:
- dealer = line[9]
- if '[Vulnerable' in line:
- reg = re.search('NS|EW|All|None', line)
- vulnerable = reg.group(0)
- 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 = SubElement(xml_root, "Deal")
- assert dealer in ["N", "E", "S", "W", ''], "Unknown Dealer {}".format(dealer)
- if dealer:
- xml_deal.attrib["Dealer"] = "West" # dict_of_hands[dealer]
- assert vulnerable in ["NS", "EW", "All", "None", ''], "Unknown vulnerable {}".format(vulnerable)
- if vulnerable:
- xml_deal.attrib['Vulnerability'] = "None" # vulnerable
- i = 0
- for hand in hands:
- if '.' in hand:
- xml_hand = SubElement(xml_deal, "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)
- # dump(xml_deal)
- i += 1
- if __name__ == '__main__':
- xml_dealsets = Element("DealSets")
- xml_dealset = SubElement(xml_dealsets, "DealSet")
- xml_dealset.attrib["ComplexityLevel"] = "1"
- xml_dealset.attrib["IBIS-ID"] = "007-Foppe-Hemminga-{}".format(date.today().strftime('%Y%m%d'))
- xml_dealset.attrib["VulnerabilityDefault"] = "None"
- SubElement(xml_dealset, "Parameters")
- process_pbn(xml_dealset)
- # dump(xml_dealsets)
- xml_tree = ElementTree(xml_dealsets)
- dom = xml.dom.minidom.parseString(tostring(xml_dealsets, encoding='utf-8', method='xml'))
- # print(dom.toprettyxml().replace('<?xml version="1.0" ?>', '<?xml version=\'1.0\' encoding=\'utf-8\'?>'))
- with open("output.xml", 'w') as f_xml:
- f_xml.write(dom.toprettyxml().replace('<?xml version="1.0" ?>', '<?xml version=\'1.0\' encoding=\'utf-8\'?>'))
- # xml_tree.write("output.xml", encoding="utf-8", xml_declaration=True)
|