print in terminal with colors:

print in terminal with colors:

# -----------------colorama模塊的一些常量---------------------------
# Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
# Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
# Style: DIM, NORMAL, BRIGHT, RESET_ALL
# author ppluer 2018/10/20
# ver:1.0
 
from colorama import  init, Fore, Back, Style

class Colored(object):
    def __init__(self):
        init(autoreset=True) 
        self.color_data=[
        {'func':self.green,'kw':['success','successfully','succeeded','enabled','true']},
        {'func':self.red,'kw':['fail','no','error','failed','false']},
        {'func':self.yellow,'kw':['warnning','warn','disabled','unknown','unable','cannot']},
        {'func':self.cyan,'kw':['info','information','starting','creating']},
        {'func':self.blue,'kw':['pass','passed']},
        {'func':self.magenta,'kw':['none','localhost','null']}
        ]
        #將函數名作爲參數存起來 我真是機智, 關鍵詞全部使用小寫 匹配的時候不分大小寫


    #  前景色:紅色  背景色:默認
    def red(self, s):
        return Style.BRIGHT+Fore.RED + s + Style.RESET_ALL  #
 
    #  前景色:綠色  背景色:默認
    def green(self, s):
        return Style.BRIGHT+Fore.GREEN + s + Style.RESET_ALL
 
    #  前景色:黃色  背景色:默認
    def yellow(self, s):
        return Style.BRIGHT+Fore.YELLOW + s + Style.RESET_ALL
 
    #  前景色:藍色  背景色:默認
    def blue(self, s):
        return Style.BRIGHT+Fore.BLUE + s + Style.RESET_ALL
 
    #  前景色:洋紅色  背景色:默認
    def magenta(self, s):
        return Style.BRIGHT+Fore.MAGENTA + s + Style.RESET_ALL
 
    #  前景色:青色  背景色:默認
    def cyan(self, s):
        return Style.BRIGHT+Fore.CYAN + s + Style.RESET_ALL
 
    #  前景色:白色  背景色:默認
    def white(self, s):
        return Style.BRIGHT+Fore.WHITE + s + Style.RESET_ALL
 
    #  前景色:黑色  背景色:默認
    def black(self, s):
        return Style.BRIGHT+Fore.BLACK
 
    #  前景色:白色  背景色:綠色
    def white_green(self, s):
        return Style.BRIGHT+Fore.WHITE + Back.GREEN + s   + Style.RESET_ALL


    def fill_color(self,wd):  #將wd與color_data內的kw對比 匹配則調用相應的function處理
        for x in self.color_data:             
            if wd.lower() in x['kw']:  #轉換成小寫匹配
                    return x['func'](wd)
            else:
                pass
        return wd     
    def capture_word(self,ba,startabc,stopabc,ba_copy):
        #ba:原字符數組
        #startabc:字母開始位置
        #stopabc:字母結束位置+1
        #ba_copy:新生成的字符數組
        length=len(ba)  
        ba_clip=bytearray()
        if startabc==stopabc:
                print('error1') 
                return
        if startabc>stopabc:
                print('error2') 
                return
        if stopabc>length: 
                print('error3') 
                return        

        for i in range(startabc,stopabc):
            ba_clip.append(ba[i])  #將ba內 range(start-stop)索引的byte 組成一個新的字符數組:ba_clip
        wd=ba_clip.decode(encoding='utf-8') #字節數組ba_clip轉換成字符串wd
        wd=self.fill_color(wd)    #wd 傳遞給fill_color
        for b in bytearray(wd,'utf-8'):   #將返回的帶color字符串wd 轉換成字節數組  再合併入ba_copy
            ba_copy.append(b)   
    def main(self,s):
        #自動根據關鍵字自動添加顏色
        ba=bytearray(s,'utf-8')
        ba_copy=bytearray()
        length=len(ba)
        startabc=0
        stopabc=0
        foundabc=False

        for i in range(length):
            if self.isabc(ba[i]):  #如果是字母  
                if not foundabc: #且之前尚未發現字母的情況下 標記開始位置 標記發現字母 ,
                    startabc=i   #已發現字母的情況下不再更新start位置 
                    foundabc=True
                if i==length-1:  #最後一個字母被發現 需要觸發stop標記 觸發capture_word
                    stopabc=length
                    self.capture_word(ba,startabc,stopabc,ba_copy)                
            else: #發現非字母 觸發標記stop  
                stopabc=i
                if foundabc: self.capture_word(ba,startabc,stopabc,ba_copy) #如前面發現字母那就觸發capture_word
                ba_copy.append(ba[i])                #將非字母copy走
                foundabc=False                          #發現字母標記爲false
        s=ba_copy.decode(encoding='utf-8')    #拷貝完轉換爲字符串
        return s

    def isabc(self,c): # my function like isalpha  處理unicode的時候比isalpha準確
        if c in range(65,91) or c in range(97,123):
            return True

if __name__=="__main__": 
    color = Colored()
    print(color.red('I am red!'))
    print(color.green('I am green!'))
    print(color.yellow('I am yellow!'))
    print(color.blue('I am blue!'))
    print(color.magenta('I am magenta!'))
    print(color.cyan('I am cyan!'))
    print(color.white('I am white!'))
    print(color.white_green('I am white green!'))
    print(color.main('i am pass passed Pass success successful SUCCESS ERROR INFO WARNnING e'))
    print(color.main('i am successful hahaha SUCCESSED!succeeded null NONE False cannot unable True'))
    print(color.main('i am successful fail error SUCCESS success'))
    print(color.main('123!@#¥%……&*()-=-=——+【】[]{}`!@#$%^&*()'))
    sss='我是張大爺123!@#¥%……&*()-=-=——+【】[]{}`!@#$%^&*()'
    ba=bytearray(sss,'utf-8')
    for i in range(len(ba)):
        if color.isabc(ba[i]):
            print('found abc index number is:',i)
    for s in sss:
        if s.isalpha():
            print('你看吧 內置的函數isaplha 遇到unicode中文發生誤判,:',s)    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章