python 美化输出信息的实例

yipeiwu_com4年前Python基础

如下所示:

# -*- coding: utf-8 -*-
# @Author: xiaodong
# @Date:  just hide
# @Last Modified by:  xiaodong
# @Last Modified time: just hide
# try:
#   from colorama import Fore, Style
# except ImportError:
#   class Temp:
#     def __getattr__(self, x):
#       return ''
#   Fore = Style = Temp()


STYLE = {
    'fore': {
        'black': 30, 'red': 31, 'green': 32, 'yellow': 33,
        'blue': 34, 'purple': 35, 'cyan': 36, 'white': 37,
    },
    'back': {
        'black': 40, 'red': 41, 'green': 42, 'yellow': 43,
        'blue': 44, 'purple': 45, 'cyan': 46, 'white': 47,
    },
    'mode': {
        'bold': 1, 'underline': 4, 'blink': 5, 'invert': 7,
    },
    'default': {
        'end': 0,
    }
}


def use_style(string, mode='', fore='', back=''):
  mode = '%s' % STYLE['mode'][mode] if mode in STYLE['mode'] else ''
  fore = '%s' % STYLE['fore'][fore] if fore in STYLE['fore'] else ''
  back = '%s' % STYLE['back'][back] if back in STYLE['back'] else ''
  style = ';'.join([s for s in [mode, fore, back] if s])
  style = '\033[%sm' % style if style else ''
  end = '\033[%sm' % STYLE['default']['end'] if style else ''
  return '%s%s%s' % (style, string, end)


def gentle_show(seq, *, column=4, fontdict=None):

  if fontdict is None:
    line_color = 'red'
    font_color = 'blue'
  elif isinstance(fontdict, dict):
    line_color = fontdict.get('line_color', 'red')
    font_color = fontdict.get('font_color', 'green')

  seq = list(map(str, seq))
  max_len = len(max(seq, key=len))

  for index, ele in enumerate(seq):
    if index % column == 0:
      print(use_style('-' * max_len * column + '-' * (column - 1), fore=line_color))
      print(use_style(ele.center(max_len, ' '), mode='bold', fore=font_color), end='|')
    else:
      if (index - column + 1) % column == 0:
        print(use_style(ele.center(max_len, ' '), mode='bold', fore=font_color))
      else:
        print(use_style(ele.center(max_len, ' '), mode='bold', fore=font_color), end='|')
  print('\n')


if __name__ == "__main__":
  gentle_show(dir([]), column=6, fontdict={'line_color': 'red', 'font_color': 'green'})
  gentle_show(range(10))

python 美化输出信息

python 美化输出信息

python 美化输出信息

以上这篇python 美化输出信息的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python使用标准库根据进程名如何获取进程的pid详解

前言 标准库是Python的一个组成部分。这些标准库是Python为你准备好的利器,可以让编程事半功倍。特别是有时候需要获取进程的pid,但又无法使用第三方库的时候。下面话不多说了,来一...

解决Mac安装scrapy失败的问题

今天打算弄个爬虫,想来想去打算用python弄一个。之前了解到scrapy这个库是个不错的选择,于是开始折腾。可惜第一步就挂了。 安装scrapy库就不成功: Installing...

Python实现K折交叉验证法的方法步骤

学习器在测试集上的误差我们通常称作“泛化误差”。要想得到“泛化误差”首先得将数据集划分为训练集和测试集。那么怎么划分呢?常用的方法有两种,k折交叉验证法和自助法。介绍这两种方法的资料有很...

Python实现把数字转换成中文

周末在家,写了个小程序,用于将阿拉伯数字转换化大写中文。程序没经过任何优化,出没经过详细的测试,挂到网上,方便将来有需要的时候直接拿来用。 #!/usr/bin/python #-*...

django框架自定义用户表操作示例

本文实例讲述了django框架自定义用户表操作。分享给大家供大家参考,具体如下: django中已经给我生成默认的User表,其中的字段已经可以满足我们的日常需求。 但有时候,我们需要更...