def list2dict(input_list): """ Create dictionary from list in format [key1, key2, score]. :param input_list: list to process :type input_list: list :returns: preprocessed dictionary :rtype: dict >>> Tools.list2dict([['f1', 'f2', 10.1], ['f3', 'f4', 20.1], \ ['f5', 'f6', 30.1], ['f1', 'f3', 40.1]]) {'f1 f2': 10.1, 'f5 f6': 30.1, 'f3 f4': 20.1, 'f1 f3': 40.1} >>> Tools.list2dict([['f1', 'f2', 10.1], ['f3', 'f4']]) Traceback (most recent call last): ... toolsException: [list2Dict] Invalid format of input list! """ dictionary = dict() for item in input_list: if len(item) != 3: raise ToolsException('[list2Dict] Invalid format ' + 'of input list!') tmp_list = [item[0], item[1]] tmp_list.sort() dictionary[tmp_list[0] + ' ' + tmp_list[1]] = item[2] return dictionary
def list_directory_by_suffix(directory, suffix): """ Return listed directory of files based on their suffix. :param directory: directory to be listed :type directory: str :param suffix: suffix of files in directory :type suffix: str :returns: list of files specified byt suffix in directory :rtype: list >>> Tools.list_directory_by_suffix('../../tests/tools', '.test') ['empty1.test', 'empty2.test'] >>> Tools.list_directory_by_suffix('../../tests/tools_no_ex', '.test') Traceback (most recent call last): ... toolsException: [listDirectoryBySuffix] No directory found! >>> Tools.list_directory_by_suffix('../../tests/tools', '.py') [] """ abs_dir = os.path.abspath(directory) try: ofiles = [f for f in listdir(abs_dir) if isfile(join(abs_dir, f))] except OSError: raise ToolsException( '[list_directory_by_suffix] No directory named {} found!'.format(directory)) out = [] for file_in in ofiles: if file_in.find(suffix) != -1: out.append(file_in) out.sort() return out
def mkdir_p(path): """ Behaviour similar to mkdir -p in shell. :param path: path to create :type path: str """ try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise ToolsException('[mkdir_p] Can not create directory!')
def get_scores(scores, key): """ Get scores from scores list by key. :param scores: input scores list :type scores: list :param key: key to find :type key: list :returns: score if key is present in score, None otherwise :rtype: float >>> Tools.get_scores([['f1', 'f2', 10.1], ['f3', 'f4', 20.1], \ ['f5', 'f6', 30.1]], ['f6', 'f5']) 30.1 """ if len(key) != 2: raise ToolsException('[getScores] Unexpected key!') if len(scores[0]) != 3: raise ToolsException('[getScores] Invalid input list!') for score in scores: a = score[0] b = score[1] if (key[0] == a and key[1] == b) or (key[0] == b and key[1] == a): return score[2] return None
def get_method(instance, method): """ Get method pointer. :param instance: input object :type instance: object :param method: name of method :type method: str :returns: pointer to method :rtype: method """ try: attr = getattr(instance, method) except AttributeError: raise ToolsException('[getMethod] Unknown class method!') return attr
def find_in_dictionary(in_dict, value): """ Find value in directory whose items are lists and return key. :param in_dict: dictionary to search in :type in_dict: dict :param value: value to find :type value: any :returns: dictionary key :rtype: any >>> Tools.find_in_dictionary({ 0 : [42], 1 : [88], 2 : [69]}, 69) 2 >>> Tools.find_in_dictionary(dict(), 69) Traceback (most recent call last): ... toolsException: [findInDictionary] Value not found! """ for key in in_dict: if value in in_dict[key]: return key raise ToolsException('[findInDictionary] Value not found!')
def get_line_from_file(line_num, infile): """ Get specified line from file. :param line_num: number of line :type line_num: int :param infile: file name :type infile: str :returns: specified line, None otherwise :rtype: str >>> Tools.get_line_from_file(3, '../../tests/tools/test.txt') 'c\\n' >>> Tools.get_line_from_file(10, '../../tests/tools/test.txt') Traceback (most recent call last): ... toolsException: [getLineFromFile] Line number not found! """ with open(infile) as fp: for i, line in enumerate(fp): if i == line_num - 1: return line raise ToolsException('[getLineFromFile] Line number not found!')
def get_nth_col(in_list, col): """ Extract n-th-1 columns from list. :param in_list: input list :type in_list: list :param col: column :type col: int :returns: list only with one column :rtype: list >>> Tools.get_nth_col([['1', '2'], ['3', '4'], ['5', '6']], col=1) ['2', '4', '6'] >>> Tools.get_nth_col([['1', '2'], ['3', '4'], ['5', '6']], col=42) Traceback (most recent call last): ... toolsException: [getNthCol] Column out of range! """ try: out = [row[col] for row in in_list] except IndexError: raise ToolsException('[getNthCol] Column out of range!') return out
def list_directory(directory): """ List directory. :param directory: directory to be listed :type directory: str :returns: list with files in directory :rtype: list >>> Utils.list_directory('../../tests/tools') ['empty1.test', 'empty2.test', 'test', 'test.txt'] >>> Utils.list_directory('../../tests/tools_no_ex') Traceback (most recent call last): ... toolsException: [listDirectory] No directory found! """ directory = os.path.abspath(directory) try: out = [f for f in listdir(directory)] except OSError: raise ToolsException('[listDirectory] No directory found!') out.sort() return out