xmlgat_to_EVT_parser.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. # %%
  2. # Imports
  3. import xml.etree.ElementTree as ET
  4. import re
  5. import json
  6. # %%
  7. # This is to handle the xmnls attribute in the TEI element in the templates
  8. uri1 = "{http://www.tei-c.org/ns/1.0}"
  9. namespaces = {
  10. '': "http://www.tei-c.org/ns/1.0",
  11. }
  12. for prefix, uri in namespaces.items():
  13. ET.register_namespace(prefix, uri)
  14. # Reference directories
  15. basedir = '../../DATA/'
  16. baseindir = basedir + 'OVI/datiniXML/xmlgat/'
  17. baseoutdir = basedir + 'OVI/datiniXML/xmlevt/'
  18. # %%
  19. # Import lems list + xml info file
  20. # get lem list as a json object
  21. lemfile = basedir + 'OVI/datiniXML/power_lemmarioB.json'
  22. lems = json.load(open(lemfile, 'r'))
  23. # Get BiblioDatini.xml, extract a list of the <Biblio> nodes with ElementTree
  24. infofile = basedir + 'OVI/datiniXML/BiblioDatini.xml'
  25. infotree = ET.parse(infofile)
  26. inforoot = infotree.getroot()
  27. infoBiblioNodeList = list(inforoot.iter('Biblio'))
  28. # %%
  29. # FUNCTIONS TO PROCESS THE XMLGAT FILEs
  30. # Get a lem index
  31. def lemIndex(lem):
  32. for item in lems:
  33. if lem.attrib['n'] in item['coordinate']:
  34. return item['id']
  35. raise ValueError("code " + lem.attrib['n'] + " not found")
  36. # Get the ElementTree node ('Element' class object) associated to an OVI sigla in the BiblioDatini.xml file
  37. def getBiblioNodeBySigla(sigla):
  38. for node in infoBiblioNodeList:
  39. for child in node:
  40. if child.tag=='sigla' and child.text==sigla:
  41. return node
  42. # Get the ElemenTree object of the whole xmlgat file corresponding to a given OVI sigla
  43. def getLetterRootFromFile(filecode, inputdirectory=baseindir):
  44. fileName = inputdirectory + 'xmlgat.' + filecode + '.xml'
  45. try:
  46. letterRoot = ET.parse(fileName).getroot()
  47. except ET.ParseError:
  48. with open(fileName, encoding="ISO-8859-1") as fp:
  49. xml_string = fp.read()
  50. xml_string = xml_string.replace('&Csic&c', "<hi rend='italic'>sic</hi>")
  51. # return xml_string
  52. letterRoot = ET.fromstring(xml_string)
  53. return letterRoot
  54. ##################################
  55. # ELABORATING LEMS IN XMLGAT FILES
  56. ##################################
  57. # PREMISE:
  58. # in the xmlgat files, the <lem> tag doesn't surround lems:
  59. #
  60. # 1. Single-word lems are in the 'tail' of the corr. lem tags, as in:
  61. # <lem>A_LEM
  62. # with no closing </lem>
  63. #
  64. # 2. Multiple-word lems are inside <w> tags immediately following the <lem>, as in:
  65. # <lem><w>A MULTIWORD LEM</w>
  66. # The body of the text is inside a single <div>
  67. # This functions puts all lems inside a <lem> tag to make xmlgat files more standard xml-compliant and easier to process, also dropping the <w> tag.
  68. # Basically:
  69. #
  70. # <lem>A_LEM --> <lem>A_LEM</lem>
  71. # <lem><w>A MULTIWORD LEM</w> --> <lem>A MULTIWORD LEM</lem>
  72. def surroundLems(letterRoot):
  73. textRoot = list(letterRoot.iter('div'))[0]
  74. texttags = [node for node in textRoot if node.tag == 'lem' or node.tag == 'w']
  75. doit = False
  76. for node in texttags:
  77. if doit and node.tag=='w':
  78. node.tag = 'NEWlem'
  79. node.attrib = prev_node.attrib
  80. prev_node.tag = 'OLDlem'
  81. if node.tag == 'lem' and node.tail != None:
  82. thelem = re.findall(r'\w+', node.tail)[0] # First word
  83. node.text = thelem
  84. node.tail = node.tail.replace(thelem, '')
  85. doit = False
  86. else:
  87. doit = True
  88. prev_node = node
  89. for node in textRoot.findall('OLDlem'):
  90. textRoot.remove(node)
  91. for node in textRoot.findall('NEWlem'):
  92. node.tag = 'lem'
  93. return textRoot
  94. # This function tries to match a lem inside <lem> node (ElementTree Element object 'node'), by its attribute 'n',
  95. # the a lem in the lem list, the json object 'lems'
  96. def getLemByCode(lem):
  97. for item in lems:
  98. if lem.attrib['n'] in item['coordinate']:
  99. return item
  100. raise ValueError("code " + lem.attrib['n'] + " not found")
  101. # Dictionary assigning to each OVI lem type a tag useful for the final TEI output
  102. lemTypeDict = {'s.m.': "sostantivo maschile", 's.f.': 'sostantivo femminile', 'antr.': 'antroponimo', 'agg.': 'aggettivo', 'n.g.': 'nome di luogo', 'v.': 'verbo'}
  103. # This function processes each lem attributes and adds more tags around the lem useful for the final TEI output
  104. def redefineLems(textRoot, fileCode):
  105. for node in textRoot.iter('lem'):
  106. node.attrib['n'] = fileCode + '_' + node.attrib['n']
  107. thisLem = getLemByCode(node)
  108. lemRef = '#' + str(thisLem['id'])
  109. node.attrib.pop('n')
  110. lemType = thisLem['lemma']['categoria']
  111. #node.attrib['type'] = lemType
  112. #sub = ET.SubElement(node, 'lem2')
  113. if lemType=='antr.':
  114. node.tag = 'persName'
  115. node.attrib['ref'] = lemRef
  116. node.attrib['type'] = lemTypeDict[lemType]
  117. elif lemType=='n.g.':
  118. node.tag = 'placeName'
  119. node.attrib['ref'] = lemRef
  120. node.attrib['type'] = lemTypeDict[lemType]
  121. else:
  122. node.tag = 'lem'
  123. node.attrib['ref'] = lemRef
  124. for lemType in lemTypeDict:
  125. node.attrib['type'] = lemType
  126. #sub.text = node.text
  127. node.text = node.text
  128. for node in textRoot.iter('lem'):
  129. node.tag = 'lem'
  130. node.attrib['ref'] = lemRef
  131. node.attrib['type'] = lemTypeDict[lemType]
  132. def replacepbcode(textRoot, fileCode):
  133. for ii, node in enumerate(textRoot.iter('pb')):
  134. node.attrib['n'] = fileCode + ' ' + str(ii + 1)
  135. def surroundPages(textRoot):
  136. # Create a new, 'clean', root
  137. newRoot = ET.fromstring("<div/>")
  138. # Add a <p/> to the new root for each page in the old one
  139. for node in textRoot.iter('pb'):
  140. ET.SubElement(newRoot, 'p')
  141. # Fill the pages in the new root
  142. page = None
  143. elementInPage = None
  144. for child in textRoot:
  145. if child.tag=='pb' and page is None:
  146. page = 0
  147. elementInPage = 0
  148. elif child.tag=='pb':
  149. page = page+1
  150. elementInPage = 0
  151. if page is not None and elementInPage is not None and child.tag!='milestone':
  152. newRoot[page].append(child)
  153. newRoot[page][elementInPage].tail = child.tail
  154. elementInPage = elementInPage+1
  155. return newRoot
  156. # Get the letter template as a string
  157. def getTemplateString():
  158. preLetterTemplateTree = ET.parse('pre_letter_template.xml')
  159. where = list( list( preLetterTemplateTree.getroot().iter(uri1+'body') )[0].iter(uri1+'div') )[0]
  160. #
  161. ET.SubElement(where, 'letterBody')
  162. #
  163. letterString = ET.tostring(preLetterTemplateTree.getroot(), encoding='unicode', method='xml')
  164. return letterString
  165. # Get a file by OVI sigla 'filecode' as an ElementTree object, process its lem, transform it to string and format it
  166. def newProcessFile(filecode, inputdirectory=baseindir):
  167. tree1 = getLetterRootFromFile(filecode, inputdirectory)
  168. #ET.dump(tree1)
  169. #
  170. textRoot1 = surroundLems(tree1)
  171. #
  172. redefineLems(textRoot1, filecode)
  173. #
  174. replacepbcode(textRoot1, filecode)
  175. #
  176. textRoot2 = surroundPages(textRoot1)
  177. #
  178. indent1 = " "
  179. textString1 = ET.tostring(textRoot2, encoding='unicode', method='xml')
  180. textString2 = textString1.replace("<lb />\n", "<lb />\n"+indent1)
  181. return textString2
  182. # %%
  183. letterTemplateString = getTemplateString()
  184. # %%
  185. # Example
  186. filecodeExample = 'j34'
  187. with open('test.xml', 'w') as f1:
  188. newString = letterTemplateString.replace('<letterBody />', newProcessFile(filecodeExample))
  189. f1.write(newString)
  190. # %%
  191. # %%