[gimp-help/wip/wormnest/python3-migration: 9/15] tools: start migration to python3 by running 2to3




commit 118d44cc668692a6762ee080812ddbf1aad3c83f
Author: Jacob Boerema <jgboerema gmail com>
Date:   Thu Feb 4 15:31:12 2021 -0500

    tools: start migration to python3 by running 2to3

 tools/show_translation_progress.py | 66 +++++++++++++++++++-------------------
 tools/validate_references.py       | 15 +++++----
 tools/xml2po.py                    | 14 ++++----
 tools/xml2po/__init__.py           | 40 +++++++++++------------
 tools/xml2po/modes/basic.py        |  2 +-
 tools/xml2po/modes/docbook.py      | 20 ++++++------
 tools/xml2po/modes/gimphelp.py     | 14 ++++----
 tools/xml_helper.py                | 36 ++++++++++-----------
 8 files changed, 104 insertions(+), 103 deletions(-)
---
diff --git a/tools/show_translation_progress.py b/tools/show_translation_progress.py
index 1839b6215..384dad805 100644
--- a/tools/show_translation_progress.py
+++ b/tools/show_translation_progress.py
@@ -40,7 +40,7 @@ class GIMPHelpXMLParser(object):
         """Returns a list of ids parsed from gimp-help.xml."""
         fh = open(self.filepath, 'r')
         dom = xml.dom.minidom.parse(fh)
-        print "Parsing XML file: %s" % os.path.basename(os.path.dirname(self.filepath))
+        print("Parsing XML file: %s" % os.path.basename(os.path.dirname(self.filepath)))
         # XXX the ids
         ids = xml.xpath.Evaluate(self.xpathexpr, dom)
         self.ids = [x.getAttribute('id') for x in ids ]
@@ -97,7 +97,7 @@ class Statistics(object):
 
     def get_ids_from_lang(self, lang):
         """Iterator over ids of given language."""
-        if lang not in self.docs.keys():
+        if lang not in list(self.docs.keys()):
             raise KeyError("%s not found in indexed documents." % lang)
         for id in self.docs[lang]:
             yield id
@@ -111,7 +111,7 @@ class Statistics(object):
         result = []
         helpids = self.hp.ids
 
-        for lang in self.docs.keys():
+        for lang in list(self.docs.keys()):
             other_ids = []
             matched = []
 
@@ -150,7 +150,7 @@ class Statistics(object):
                              " Language. Maybe you need to build the HTML"
                              " docs? Check if gimp-help.xml files exist.")
 
-        for lang in self.docs.keys():
+        for lang in list(self.docs.keys()):
             invalid = []
             skip = ['faq', 'using', 'fdl', 'glossary',
                 'introduction', 'gimp-main', 'legal', 'tools-color',
@@ -162,8 +162,8 @@ class Statistics(object):
                 if id in skip:
                     continue
 
-                not_invalid = filter(lambda k, y=0:\
-                    y + self._is_substring(id, k), skip)
+                not_invalid = list(filter(lambda k, y=0:\
+                    y + self._is_substring(id, k), skip))
 
                 if not_invalid:
                     continue
@@ -204,11 +204,11 @@ class Statistics(object):
                     names[id] = os.path.join(root, file)
 
         # remove the valid entries
-        for id in names.keys():
+        for id in list(names.keys()):
             not_invalid = 0
 
-            not_invalid = filter(lambda k, y=0:\
-                y + self._is_substring(id, k), filter_files)
+            not_invalid = list(filter(lambda k, y=0:\
+                y + self._is_substring(id, k), filter_files))
             if not_invalid:
                 continue
 
@@ -226,41 +226,41 @@ class Statistics(object):
         invalid_ids = self.getInvalidIds()
         invalid_files = self.getInvalidFilenames()
 
-        print "General statistics:"
-        print "==================="
+        print("General statistics:")
+        print("===================")
 
         for dict in self.statistics:
             done = '#'*int(dict['prc_done']/10)
             todo = ' '*(10-(dict['prc_done']/10))
-            print "\nLanguage: %s" %dict['lang']
-            print "Found titles for: %i ids - Todo: %s ids - other ids: %s"\
-                %(dict['done'], dict['todo'], dict['others'])
-            print "Percent done: |%s%s| %s%%" %(done,todo, dict['prc_done'])
+            print("\nLanguage: %s" %dict['lang'])
+            print("Found titles for: %i ids - Todo: %s ids - other ids: %s"\
+                %(dict['done'], dict['todo'], dict['others']))
+            print("Percent done: |%s%s| %s%%" %(done,todo, dict['prc_done']))
 
-        print "\n\nInvalid ids:"
-        print "================"
-        print "Found %i ids which are not part of gimphelp-ids.h" %len(invalid_ids)
+        print("\n\nInvalid ids:")
+        print("================")
+        print("Found %i ids which are not part of gimphelp-ids.h" %len(invalid_ids))
 
         if print_invalid:
             invalid_ids.reverse()
             for id in invalid_ids:
-                print "%s" %id
+                print("%s" %id)
         else:
-            print "Hint: start the program again with parameter >>-i<<",
-            print "if you want to view them."
+            print("Hint: start the program again with parameter >>-i<<", end=' ')
+            print("if you want to view them.")
 
-        print "\n\nInvalid filenames:"
-        print "======================"
-        print "Found %i filenames which are not part of gimphelp-ids.h" %len(invalid_files)
+        print("\n\nInvalid filenames:")
+        print("======================")
+        print("Found %i filenames which are not part of gimphelp-ids.h" %len(invalid_files))
 
         if print_invalid:
-            keys = invalid_files.keys()
+            keys = list(invalid_files.keys())
             keys.sort()
             for k in keys:
-                print "%s -> %s" %(k, invalid_files[k])
+                print("%s -> %s" %(k, invalid_files[k]))
         else:
-            print "Hint: start the program again with parameter >>-i<<",
-            print "if you want to view them."
+            print("Hint: start the program again with parameter >>-i<<", end=' ')
+            print("if you want to view them.")
 
     def _makedict(self, **kwargs):
         return kwargs
@@ -277,7 +277,7 @@ class Statistics(object):
 def get_linguas(gimphelppath):
     """ returns the linguas set in configure.in in gimp-help-2 dir """
     gimphelppath = os.path.join(gimphelppath, "html")
-    if os.environ.has_key('ALL_LINGUAS'):
+    if 'ALL_LINGUAS' in os.environ:
         linguas = os.environ.get('ALL_LINGUAS')
         linguas = linguas.split(' ')
         return linguas 
@@ -324,13 +324,13 @@ def main():
         sys.exit(1)
     else:
         usage()
-        print "Error: one of your path is invalid!"
+        print("Error: one of your path is invalid!")
         sys.exit(0)
 
 
 def usage(errormsg=None):
     
-    print """idlookup.py - Copyright 2004 Roman Joost (gimp-help-2)
+    print("""idlookup.py - Copyright 2004 Roman Joost (gimp-help-2)
 generates some statistical information about the documentation process 
 
 usage: idlookup.py [options]
@@ -339,9 +339,9 @@ usage: idlookup.py [options]
         -g      path to the GIMP sources (eg. /opt/gimp)
         -x      path to the gimp-help-2 sources (eg. /opt/gimp-help-2)
         -i      print ids which are supposed to be invalid
-        -h      this help"""
+        -h      this help""")
     if errormsg:
-        print "\nError: %s" % errormsg
+        print("\nError: %s" % errormsg)
 
 if __name__ == "__main__":
     main()
diff --git a/tools/validate_references.py b/tools/validate_references.py
index 14b210a30..8d7ac7359 100644
--- a/tools/validate_references.py
+++ b/tools/validate_references.py
@@ -58,7 +58,7 @@ class FileNameContainer(object):
 
     def __contains__(self, key):
         """Is there an entry 'key'?."""
-        return self.data.has_key(key)
+        return key in self.data
 
     def __setitem__(self, key, val):
         """Add a (key, value) pair to the container, e.g.
@@ -152,7 +152,7 @@ class ImageFilesList(FileNameContainer):
                     (len(files), char_if("s", len(files) != 1),
                                  char_if(":", len(files) != 0)))
         for imagefile in sorted(files):
-            print "ORPHANED:", os.path.join(self.imageroot, imagefile)
+            print("ORPHANED:", os.path.join(self.imageroot, imagefile))
 
 
 class ImageReferencesList(FileNameContainer):
@@ -196,7 +196,7 @@ class ImageReferencesList(FileNameContainer):
 
         try:
             self.parser.parse(source_file)
-        except xml.sax.SAXException, err:
+        except xml.sax.SAXException as err:
             Logger.error("ERROR parsing %s" % err)
             sys.exit(65)
         except:
@@ -228,7 +228,7 @@ class ImageReferencesList(FileNameContainer):
                     (len(files), char_if("s", len(files) != 1),
                                  char_if(":", len(files) != 0)))
         for imagefile in sorted(files):
-            print "BROKEN: images/%s IN %s" % (imagefile, self.data[imagefile])
+            print("BROKEN: images/%s IN %s" % (imagefile, self.data[imagefile]))
 
     # Internal stack methods to keep track of the opened files
 
@@ -261,7 +261,7 @@ class XMLHandler(xml.sax.handler.ContentHandler):
                     self.owner.add(fileref)
             except KeyError:
                 self.error("missing 'fileref' attribute")
-        if name == "xi:include" and attrs.has_key('href'):
+        if name == "xi:include" and 'href' in attrs:
             filename = os.path.join(os.path.dirname(self.owner.current_file()),
                                     attrs.getValue('href'))
             if os.path.isfile(filename):
@@ -319,7 +319,7 @@ def main():
                          ["help", "verbose",
                           "root=", "xmldir=", "srcdir=", "file=",
                           "broken", "links", "orphaned",])
-    except getopt.GetoptError, err:
+    except getopt.GetoptError as err:
         usage(64, str(err))
 
     for opt, arg in opts:
@@ -352,7 +352,8 @@ def main():
     if gimp_help_root_dir != ".":
         try:
             os.chdir(gimp_help_root_dir)
-        except OSError, (errno, strerror):
+        except OSError as xxx_todo_changeme:
+            (errno, strerror) = xxx_todo_changeme.args
             Logger.error("ERROR: %s: %s" % (strerror, gimp_help_root_dir))
             sys.exit(errno)
 
diff --git a/tools/xml2po.py b/tools/xml2po.py
index 037e61f27..b3e110dc3 100755
--- a/tools/xml2po.py
+++ b/tools/xml2po.py
@@ -41,9 +41,9 @@ NULL_STRING = '/dev/null'
 if not os.path.exists('/dev/null'): NULL_STRING = 'NUL'
 
 def usage (with_help = False):
-    print >> sys.stderr, "Usage:  %s [OPTIONS] [XMLFILE]..." % (sys.argv[0])
+    print("Usage:  %s [OPTIONS] [XMLFILE]..." % (sys.argv[0]), file=sys.stderr)
     if with_help:
-        print >> sys.stderr, """
+        print("""
 OPTIONS may be some of:
     -a    --automatic-tags     Automatically decides if tags are to be considered
                                  "final" or not
@@ -72,7 +72,7 @@ EXAMPLES:
     using -p option for each XML file:
         %(command)s -p de.po chapter1.xml > chapter1.de.xml
         %(command)s -p de.po chapter2.xml > chapter2.de.xml
-""" % {'command': sys.argv[0]}
+""" % {'command': sys.argv[0]}, file=sys.stderr)
 
 
 def main(argv):
@@ -148,7 +148,7 @@ def main(argv):
             sys.exit(0)
 
     if operation == 'update' and output != "-":
-        print >> sys.stderr, "Option '-o' is not yet supported when updating translations directly. Ignoring 
this option."
+        print("Option '-o' is not yet supported when updating translations directly. Ignoring this option.", 
file=sys.stderr)
 
     # Treat remaining arguments as XML files
     filenames = []
@@ -158,16 +158,16 @@ def main(argv):
     try:
         xml2po_main = Main(default_mode, operation, output, options)
     except IOError:
-        print >> sys.stderr, "Error: cannot open file %s for writing." % (output)
+        print("Error: cannot open file %s for writing." % (output), file=sys.stderr)
         sys.exit(5)
 
     if operation == 'merge':
         if len(filenames) > 1:
-            print  >> sys.stderr, "Error: You can merge translations with only one XML file at a time."
+            print("Error: You can merge translations with only one XML file at a time.", file=sys.stderr)
             sys.exit(2)
 
         if not mofile:
-            print >> sys.stderr, "Error: You must specify MO file when merging translations."
+            print("Error: You must specify MO file when merging translations.", file=sys.stderr)
             sys.exit(3)
 
         xml2po_main.merge(mofile, filenames[0])
diff --git a/tools/xml2po/__init__.py b/tools/xml2po/__init__.py
index eec197947..7a07eb226 100644
--- a/tools/xml2po/__init__.py
+++ b/tools/xml2po/__init__.py
@@ -86,14 +86,14 @@ class MessageOutput:
                 self.messages.append(t)
                 if spacepreserve:
                     self.nowrap[t] = True
-                if t in self.linenos.keys():
+                if t in list(self.linenos.keys()):
                     self.linenos[t].append((self.filename, tag, lineno))
                 else:
                     self.linenos[t] = [ (self.filename, tag, lineno) ]
                 if (not self.do_translations) and comment and not t in self.comments:
                     self.comments[t] = comment
             else:
-                if t in self.linenos.keys():
+                if t in list(self.linenos.keys()):
                     self.linenos[t].append((self.filename, tag, lineno))
                 else:
                     self.linenos[t] = [ (self.filename, tag, lineno) ]
@@ -166,7 +166,7 @@ class XMLDocument(object):
         elif node.isText():
             if node.isBlankNode():
                 if self.app.options.get('expand_entities') or \
-                  (not (node.prev and not node.prev.isBlankNode() and node.next and not 
node.next.isBlankNode()) ):
+                  (not (node.prev and not node.prev.isBlankNode() and node.__next__ and not 
node.next.isBlankNode()) ):
                     #print >>sys.stderr, "BLANK"
                     node.setContent('')
             else:
@@ -176,7 +176,7 @@ class XMLDocument(object):
             child = node.children
             while child:
                 self.normalizeNode(child)
-                child = child.next
+                child = child.__next__
 
     def normalizeString(self, text, spacepreserve = False):
         """Normalizes string to be used as key for gettext lookup.
@@ -200,7 +200,7 @@ class XMLDocument(object):
             tree = ctxt.doc()
             newnode = tree.getRootElement()
         except:
-            print >> sys.stderr, """Error while normalizing string as XML:\n"%s"\n""" % (text)
+            print("""Error while normalizing string as XML:\n"%s"\n""" % (text), file=sys.stderr)
             return text
 
         self.normalizeNode(newnode)
@@ -209,7 +209,7 @@ class XMLDocument(object):
         child = newnode.children
         while child:
             result += child.serialize('utf-8')
-            child = child.next
+            child = child.__next__
 
         result = re.sub('^ ','', result)
         result = re.sub(' $','', result)
@@ -235,7 +235,7 @@ class XMLDocument(object):
         ctxt.parseDocument()
         tree = ctxt.doc()
         if next:
-            newnode = tree.children.next
+            newnode = tree.children.__next__
         else:
             newnode = tree.children
 
@@ -243,7 +243,7 @@ class XMLDocument(object):
         child = newnode.children
         while child:
             result += child.serialize('utf-8')
-            child = child.next
+            child = child.__next__
         tree.freeDoc()
         return result
 
@@ -262,7 +262,7 @@ class XMLDocument(object):
                         result += child.content.decode('utf-8')
                 else:
                     result += self.myAttributeSerialize(child)
-                child = child.next
+                child = child.__next__
         else:
             result = node.serialize('utf-8')
         return result
@@ -338,7 +338,7 @@ class XMLDocument(object):
                 pass
 
             if not newnode:
-                print >> sys.stderr, """Error while parsing translation as XML:\n"%s"\n""" % 
(text.encode('utf-8'))
+                print("""Error while parsing translation as XML:\n"%s"\n""" % (text.encode('utf-8')), 
file=sys.stderr)
                 return
 
             newelem = newnode.getRootElement()
@@ -346,13 +346,13 @@ class XMLDocument(object):
             if newelem and newelem.children:
                 free = node.children
                 while free:
-                    next = free.next
+                    next = free.__next__
                     free.unlinkNode()
                     free = next
 
                 if node:
                     copy = newelem.copyNodeList()
-                    next = node.next
+                    next = node.__next__
                     node.replaceNode(newelem.copyNodeList())
                     node.next = next
 
@@ -377,7 +377,7 @@ class XMLDocument(object):
             if child.isText() and child.content.strip() != '':
                 return True
             else:
-                child = child.next
+                child = child.__next__
         return False
 
 
@@ -441,7 +441,7 @@ class XMLDocument(object):
                     outtxt += '<%s>%s</%s>' % (starttag, content, endtag)
                 else:
                     outtxt += self.doSerialize(child)
-            child = child.next
+            child = child.__next__
 
         if self.app.operation == 'merge':
             norm_outtxt = self.normalizeString(outtxt, self.app.isSpacePreserveNode(node))
@@ -521,7 +521,7 @@ class XMLDocument(object):
             outtxt = ''
             while child:
                 outtxt += self.doSerialize(child)
-                child = child.next
+                child = child.__next__
             return outtxt
 
 def xml_error_handler(arg, ctxt):
@@ -565,7 +565,7 @@ class Main(object):
             try:
                 doc = XMLDocument(xmlfile, self)
             except Exception as e:
-                print >> sys.stderr, "Unable to parse XML file '%s': %s" % (xmlfile, str(e))
+                print("Unable to parse XML file '%s': %s" % (xmlfile, str(e)), file=sys.stderr)
                 sys.exit(1)
             self.current_mode.preProcessXml(doc.doc, self.msg)
             doc.generate_messages()
@@ -578,13 +578,13 @@ class Main(object):
         try:
             doc = XMLDocument(xmlfile, self)
         except Exception as e:
-            print >> sys.stderr, str(e)
+            print(str(e), file=sys.stderr)
             sys.exit(1)
 
         try:
             mfile = open(mofile, "rb")
         except:
-            print >> sys.stderr, "Can't open MO file '%s'." % (mofile)
+            print("Can't open MO file '%s'." % (mofile), file=sys.stderr)
         self.gt = gettext.GNUTranslations(mfile)
         self.gt.add_fallback(NoneTranslations())
         # Has preProcessXml use cases for merge?
@@ -607,7 +607,7 @@ class Main(object):
         try:
             doc = XMLDocument(xmlfile, self)
         except Exception as e:
-            print >> sys.stderr, str(e)
+            print(str(e), file=sys.stderr)
             sys.exit(1)
         doc.generate_messages()
 
@@ -615,7 +615,7 @@ class Main(object):
         try:
             doc = XMLDocument(origxml, self)
         except Exception as e:
-            print >> sys.stderr, str(e)
+            print(str(e), file=sys.stderr)
             sys.exit(1)
         doc.generate_messages()
         self.output_po()
diff --git a/tools/xml2po/modes/basic.py b/tools/xml2po/modes/basic.py
index e2ef7a473..d9b318848 100644
--- a/tools/xml2po/modes/basic.py
+++ b/tools/xml2po/modes/basic.py
@@ -42,7 +42,7 @@ class basicXmlMode:
             while child and final_children:
                 if not child.isBlankNode() and child.type != 'comment' and not self.isFinalNode(child):
                     final_children = False
-                child = child.next
+                child = child.__next__
             if final_children:
                 return True
         return False
diff --git a/tools/xml2po/modes/docbook.py b/tools/xml2po/modes/docbook.py
index 276a9d9bb..5658ffc1a 100644
--- a/tools/xml2po/modes/docbook.py
+++ b/tools/xml2po/modes/docbook.py
@@ -43,7 +43,7 @@ try:
 except ImportError:
     from md5 import new as md5_new
 
-from basic import basicXmlMode
+from .basic import basicXmlMode
 
 class docbookXmlMode(basicXmlMode):
     """Class for special handling of DocBook document types.
@@ -95,7 +95,7 @@ class docbookXmlMode(basicXmlMode):
             ret = self._find_articleinfo(child)
             if ret:
                 return ret
-            child = child.next
+            child = child.__next__
         return None
 
     def _find_lastcopyright(self, node):
@@ -131,7 +131,7 @@ class docbookXmlMode(basicXmlMode):
                     hash = self._md5_for_file(fullpath)
                 else:
                     hash = "THIS FILE DOESN'T EXIST"
-                    print >>sys.stderr, "Warning: image file '%s' not found." % fullpath
+                    print("Warning: image file '%s' not found." % fullpath, file=sys.stderr)
 
                 msg.outputMessage("@@image: '%s'; md5=%s" % (attr, hash), node.lineNo(),
                                   "When image changes, this message will be marked fuzzy or untranslated for 
you.\n"+
@@ -140,7 +140,7 @@ class docbookXmlMode(basicXmlMode):
             child = node.children
             while child:
                 self._output_images(child,msg)
-                child = child.next
+                child = child.__next__
 
 
     def preProcessXml(self, doc, msg):
@@ -157,7 +157,7 @@ class docbookXmlMode(basicXmlMode):
         root = doc.getRootElement()
         # DocBook documents can be something other than article, handle that as well in the future
         while root and root.name != 'article' and root.name != 'book':
-            root = root.next
+            root = root.__next__
         if root and (root.name == 'article' or root.name == 'book'):
             root.setProp('lang', language)
         else:
@@ -198,10 +198,10 @@ class docbookXmlMode(basicXmlMode):
 # Perform some tests when ran standalone
 if __name__ == '__main__':
     test = docbookXmlMode()
-    print "Ignored tags       : " + repr(test.getIgnoredTags())
-    print "Final tags         : " + repr(test.getFinalTags())
-    print "Space-preserve tags: " + repr(test.getSpacePreserveTags())
+    print("Ignored tags       : " + repr(test.getIgnoredTags()))
+    print("Final tags         : " + repr(test.getFinalTags()))
+    print("Space-preserve tags: " + repr(test.getSpacePreserveTags()))
 
-    print "Credits from string: '%s'" % test.getStringForTranslators()
-    print "Explanation for credits:\n\t'%s'" % test.getCommentForTranslators()
+    print("Credits from string: '%s'" % test.getStringForTranslators())
+    print("Explanation for credits:\n\t'%s'" % test.getCommentForTranslators())
 
diff --git a/tools/xml2po/modes/gimphelp.py b/tools/xml2po/modes/gimphelp.py
index c751d253c..17bd5a926 100644
--- a/tools/xml2po/modes/gimphelp.py
+++ b/tools/xml2po/modes/gimphelp.py
@@ -31,7 +31,7 @@ try:
 except ImportError:
     from md5 import new as md5_new
 
-from docbook import docbookXmlMode
+from .docbook import docbookXmlMode
 
 class gimphelpXmlMode(docbookXmlMode):
     """Class for special handling of gimp-help DocBook document types.
@@ -81,7 +81,7 @@ class gimphelpXmlMode(docbookXmlMode):
             child = node.children
             while child:
                 self._output_images(child,msg)
-                child = child.next
+                child = child.__next__
 
     def preProcessXml(self, doc, msg):
         """Add additional messages of interest here."""
@@ -91,10 +91,10 @@ class gimphelpXmlMode(docbookXmlMode):
 # Perform some tests when ran standalone
 if __name__ == '__main__':
     test = gimphelpXmlMode()
-    print "Ignored tags       : " + repr(test.getIgnoredTags())
-    print "Final tags         : " + repr(test.getFinalTags())
-    print "Space-preserve tags: " + repr(test.getSpacePreserveTags())
+    print("Ignored tags       : " + repr(test.getIgnoredTags()))
+    print("Final tags         : " + repr(test.getFinalTags()))
+    print("Space-preserve tags: " + repr(test.getSpacePreserveTags()))
 
-    print "Credits from string: '%s'" % test.getStringForTranslators()
-    print "Explanation for credits:\n\t'%s'" % test.getCommentForTranslators()
+    print("Credits from string: '%s'" % test.getStringForTranslators())
+    print("Explanation for credits:\n\t'%s'" % test.getCommentForTranslators())
 
diff --git a/tools/xml_helper.py b/tools/xml_helper.py
index f6b1ef818..26fa06b28 100644
--- a/tools/xml_helper.py
+++ b/tools/xml_helper.py
@@ -98,7 +98,7 @@ def parse_ids (document):
 
 def get_node_by_id (document, id):
     for node in document.getiterator ():
-        if node.attrib.has_key (IDTAG) and \
+        if IDTAG in node.attrib and \
            node.attrib[IDTAG] == id:
             return node
     return None
@@ -106,14 +106,14 @@ def get_all_langs (document):
     """Rerieve all languages in use  a document"""
     langs = {}
     for node in document.get_iterator():
-        if node.attrib.has_key ("lang"):
+        if "lang" in node.attrib:
             if ";" in node.attrib["lang"]:
                 local_langs = node.attrib["lang"].split(";")
             else:
                 local_langs = [node.attrib["lang"]]
             for local_lang in local_langs:
                 langs[local_lang] = None
-    return langs.keys ()
+    return list(langs.keys ())
 
 def node_replace (parent_node, old_node, new_node):
     parent_node.insert (parent_node.getchildren().index(old_node), new_node)
@@ -149,7 +149,7 @@ def create_ids (path, document):
     idcount = 1
     for node in document.getiterator ():
         node_hash = str (ET.tostring(node, "utf-8").__hash__())
-        if not all_hashes.has_key (node_hash):
+        if node_hash not in all_hashes:
             node.attrib [CHANGEDTAG] = "True"
         node.attrib [IDTAG] = str (idcount)
         node.attrib [HASHTAG] = node_hash
@@ -158,16 +158,16 @@ def create_ids (path, document):
 def remove_ids (document):
     for node in document.getiterator ():
         for attrib in (CHANGEDTAG, HASHTAG, IDTAG):
-            if node.attrib.has_key (attrib):
+            if attrib in node.attrib:
                 del node.attrib [attrib]
 
 
 def remove_hashes (document):
     for node in document.getiterator ():
-        if node.attrib.has_key (HASHTAG):
+        if HASHTAG in node.attrib:
             del node.attrib [HASHTAG]
-        if (node.attrib.has_key (IDTAG) and
-            not node.attrib.has_key ("lang") and
+        if (IDTAG in node.attrib and
+            "lang" not in node.attrib and
             not node.getchildren()
             ):
             del node.attrib [IDTAG]
@@ -183,7 +183,7 @@ def _sort_nodes (node_list):
     for i, node in enumerate (node_list):
         reindex [node.xml_helper_order] = i
     new_list = []
-    sorted_keys = reindex.keys()[:]
+    sorted_keys = list(reindex.keys())[:]
     sorted_keys.sort()
     for key in sorted_keys:
         new_list.append (node_list[reindex[key]])
@@ -193,7 +193,7 @@ def _sort_nodes (node_list):
 
 def recurse_rip (parent, element, all_langs):
     element.children_langs = {}
-    if not element.attrib.has_key ("lang"):
+    if "lang" not in element.attrib:
         for child in element.getchildren()[:]:
             recurse_rip (element, child, all_langs)
     else:
@@ -225,7 +225,7 @@ def count_children_lang (node):
         if first:
             first = False
             continue
-        if node.attrib.has_key("lang"):
+        if "lang" in node.attrib:
             count += 1
     return count
 
@@ -237,7 +237,7 @@ def merge_docs (helper_document, translated_document, merge_langs):
         #this extra attribute is retrieved in the sorting
         #by lang attributes routine to assure the same
         #document order of the nodes with the same lang.
-        if not node.attrib.has_key ("lang"):
+        if "lang" not in node.attrib:
             continue
         if (len (node.attrib["lang"].split(";") ) > 1 and
             len (node.getchildren ())  and
@@ -254,7 +254,7 @@ def merge_docs (helper_document, translated_document, merge_langs):
             continue
         #if it got here, current node in document is to be
         #merged into helper_document
-        if node.attrib.has_key (IDTAG):
+        if IDTAG in node.attrib:
             node_to_be_replaced = all_ids [node.attrib[IDTAG]]
             node_replace (node_to_be_replaced.parent, node_to_be_replaced, node)
         else:
@@ -263,7 +263,7 @@ def merge_docs (helper_document, translated_document, merge_langs):
             found = False
             while address_node.previous_sibling != None:
                 address_node = address_node.previous_sibling
-                if address_node.attrib.has_key (IDTAG):
+                if IDTAG in address_node.attrib:
                     prev_id = address_node.attrib[IDTAG]
                     where_to_insert = all_ids [prev_id]
                     found = True
@@ -307,7 +307,7 @@ def format_xml (node):
             child_langs = []
             nodes_by_lang = {}
             group = child.tag
-        if child.attrib.has_key ("lang"):
+        if "lang" in child.attrib:
 
             lang = child.attrib["lang"]
             if len (lang.split (";")) > 1:
@@ -386,7 +386,7 @@ def create_missing_tags (node, all_langs):
             for lang in all_langs:
                 group_langs[lang] =  []
             group = child.tag
-        if child.attrib.has_key ("lang"):
+        if "lang" in child.attrib:
             lang = child.attrib["lang"]
             if len (lang.split (";")) > 1:
                 local_langs = lang.split (";")
@@ -646,7 +646,7 @@ if __name__=="__main__":
            help ()
            sys.exit(0)
        elif option == "--version":
-           print "xml_helper version %s\nby João S. O. Bueno Calligaris (c) 2006" % version
+           print("xml_helper version %s\nby João S. O. Bueno Calligaris (c) 2006" % version)
            sys.exit(0)
        elif option[:2] != "--":
            in_files.append (option)
@@ -663,5 +663,5 @@ if __name__=="__main__":
         format_files (in_files)
     else:
         short_help()
-        print options, langs
+        print(options, langs)
         sys.exit (1)
\ No newline at end of file


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]