Guest User

Untitled

a guest
Jan 17th, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. import re
  2. import logging
  3. from xml.dom.minidom import parse as xmlparse
  4.  
  5.  
  6. class FileError(Exception):
  7. pass
  8.  
  9.  
  10. class FileIOError(IOError):
  11. pass
  12.  
  13.  
  14. class UnsupportedFiletypeError(FileError):
  15. pass
  16.  
  17.  
  18. class NotEnoughFilesError(FileError):
  19. pass
  20.  
  21.  
  22. class Pair:
  23. def __init__(self, a, b):
  24. self.a = a
  25. self.b = b
  26.  
  27. def __str__(self):
  28. return '{}, {}'.format(self.a, self.b)
  29.  
  30. def __getitem__(self, key):
  31. if not isinstance(key, int):
  32. raise TypeError('`key` must be of type integer.')
  33. if key not in [0, 1]:
  34. raise IndexError('Expecting an index of 0 and 1, but found {}.'.format(key))
  35.  
  36. if key == 0:
  37. return self.a
  38. return self.b
  39.  
  40.  
  41. def prettyformatxml(path, encoding=None):
  42. """
  43. Takes a one line xml file and splits it into many.
  44. Formats the xml to be more readable.
  45. :param path: path to file as a string.
  46. :return: the prettier xml.
  47. """
  48. return xmlparse(path, encoding).toprettyxml(indent=' '*2)
  49.  
  50.  
  51. def prettyfilexml(path, encoding=None):
  52. """
  53. Takes a one line xml file and splits it into many.
  54. Formats the xml to be more readable.
  55. :param path: path to file as a string.
  56. :return: None.
  57. """
  58. xml_str = prettyformatxml(path, encoding).encode(encoding or 'utf-8')
  59. # TODO: We should still write to the file in blocks, not all at once.
  60. with open(path, 'wb') as xml:
  61. xml.write(xml_str)
  62.  
  63.  
  64. def dict_verify(dictionary, kws):
  65. pure_kws = [x.split('=')[0] if '=' in x else x for x in kws]
  66. # First we check for default values
  67. for item in [x for x in kws if '=' in x]:
  68. key, value = item.split('=')
  69. dictionary[key] = value
  70.  
  71. # Then we verify that the dictionary has the proper values
  72. for key, _ in dictionary.items():
  73. if key not in pure_kws:
  74. raise ValueError('Key `{}` not in acceptable keywords.'.format(key))
  75.  
  76.  
  77. def sdv(d, reverse=False):
  78. """Sort a dictionary by value and return a representation
  79. of it as a list.
  80. :param d: the dictionary to sort
  81. :param reverse: whether to reverse the order. Default is false.
  82. :returns: a sorted list.
  83. """
  84. return sorted(d.items(), key=lambda t: t[1], reverse=reverse)
Add Comment
Please, Sign In to add comment