Created
January 16, 2019 22:05
-
-
Save blakesanie/16eb40dd9148171cc373ec0f382a07cd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import re | |
| import logging | |
| from xml.dom.minidom import parse as xmlparse | |
| class FileError(Exception): | |
| pass | |
| class FileIOError(IOError): | |
| pass | |
| class UnsupportedFiletypeError(FileError): | |
| pass | |
| class NotEnoughFilesError(FileError): | |
| pass | |
| class Pair: | |
| def __init__(self, a, b): | |
| self.a = a | |
| self.b = b | |
| def __str__(self): | |
| return '{}, {}'.format(self.a, self.b) | |
| def __getitem__(self, key): | |
| if not isinstance(key, int): | |
| raise TypeError('`key` must be of type integer.') | |
| if key not in [0, 1]: | |
| raise IndexError('Expecting an index of 0 and 1, but found {}.'.format(key)) | |
| if key == 0: | |
| return self.a | |
| return self.b | |
| def prettyformatxml(path, encoding=None): | |
| """ | |
| Takes a one line xml file and splits it into many. | |
| Formats the xml to be more readable. | |
| :param path: path to file as a string. | |
| :return: the prettier xml. | |
| """ | |
| return xmlparse(path, encoding).toprettyxml(indent=' '*2) | |
| def prettyfilexml(path, encoding=None): | |
| """ | |
| Takes a one line xml file and splits it into many. | |
| Formats the xml to be more readable. | |
| :param path: path to file as a string. | |
| :return: None. | |
| """ | |
| xml_str = prettyformatxml(path, encoding).encode(encoding or 'utf-8') | |
| # TODO: We should still write to the file in blocks, not all at once. | |
| with open(path, 'wb') as xml: | |
| xml.write(xml_str) | |
| def dict_verify(dictionary, kws): | |
| pure_kws = [x.split('=')[0] if '=' in x else x for x in kws] | |
| # First we check for default values | |
| for item in [x for x in kws if '=' in x]: | |
| key, value = item.split('=') | |
| dictionary[key] = value | |
| # Then we verify that the dictionary has the proper values | |
| for key, _ in dictionary.items(): | |
| if key not in pure_kws: | |
| raise ValueError('Key `{}` not in acceptable keywords.'.format(key)) | |
| def sdv(d, reverse=False): | |
| """Sort a dictionary by value and return a representation | |
| of it as a list. | |
| :param d: the dictionary to sort | |
| :param reverse: whether to reverse the order. Default is false. | |
| :returns: a sorted list. | |
| """ | |
| return sorted(d.items(), key=lambda t: t[1], reverse=reverse) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment