defpretty_col(rows, title=True, print_title=True, fields=None): """ :param rows: List[List] or List[Dict] type :param title: whether row0 is title or not. always True when <rows> is List[Dict] type :param print_title: print title or not when <title> is True, :param fields: specify columns order :return: """
defstr_width(string): count = 0 for ch in string.decode('utf8') if is_py2 else string: if is_zh(ch): count += 2 else: count += 1 return count
if len(rows) == 0: return
row_list = rows # if type(rows[0]) is dict: # if isinstance(rows[0], OrderedDict) or isinstance(rows[0], dict): if type(rows[0]).__name__ in ["dict", "OrderedDict"]: title = True ifnot fields: fields = rows[0].keys() row_list = [[d.get(k) for k in fields] for d in rows] row_list.insert(0, fields)
if type(rows[0]) is list: if fields: fields_cols = fields if isinstance(fields[0], str): row0 = rows[0] fields_cols = [row0.index(m) for m in fields] row_list = [[r[i] for i in fields_cols] for r in row_list]
columns_list = list(zip(*row_list)) c_len = [max(map(str_width, col)) for col in columns_list] c_len = [w + 4 - w % 4for w in c_len] r_len = sum(c_len) - 2
nr = 0 for row in row_list: nr += 1 line = "".join([x + " " * (c_len[i] - str_width(x)) for i, x in enumerate(row)]) if1 == nr and title: if print_title: print(line) print("*" * r_len) continue print(line)
defshow_all(): with(open("contact.txt", "r")) as f: name_dict_list = list(csv.DictReader(f))