Skip to content

Instantly share code, notes, and snippets.

@huseyin
Last active November 14, 2015 20:07
Show Gist options
  • Save huseyin/fcd0b94d3b121a199da7 to your computer and use it in GitHub Desktop.
Save huseyin/fcd0b94d3b121a199da7 to your computer and use it in GitHub Desktop.
ıvır zıvır işler
import re
import __builtin__
class ColorizeString(str):
def colorize(self, color=None, **kwcolors):
if color is not None:
kwcolors = None
# Renk argüman olarak alınırken bir dict değil ise mutlak suretle
# string tipli olmalıdır.
if not isinstance(color, basestring):
raise TypeError('%s: invalid type' %type(color))
self.color = color
else:
try:
self.color = kwcolors['color']
except KeyError:
raise(KeyError(
'%s: \'%s\': invalid key' %(type(self).__name__, kwcolors.keys()[0])))
# Argüman olarak paslanan renk adı renkler (__color_codes)
# yapımızda bulunuyor mu kontrol et.
if self.color not in self.__color_codes():
raise ValueError('%s: no color alias' %self.color)
else:
self.code = self.__color_codes()[self.color]
# String daha önceden renklendirilmiş mi kontrol et. Eğer
# renklendirilmiş ise spesifik davranış sergile.
if self.colorized():
return self.__recolorize()
else:
return "\033[38;5;%dm%s\033[0m" % (self.code, self)
def colorized(self):
""" colorized() """
if re.search("\033\[[0-9;]+m", self) is not None:
return True
else:
return False
def colors(self):
""" colors() """
return self.__color_codes()
@staticmethod
def methods():
""" methods() """
return str.__dict__
@classmethod
def str_colors(cls):
""" str_colors() """
return cls(str("").colors())
def __recolorize(self):
""" __recolorize() """
text = re.search("\033\[([0-9;]+)m(.*?)\033\[0m", self).group(2)
return str(text).colorize(self.color)
def __color_codes(self):
""" __color_codes() """
return {
'black': 233,
'white': 255,
'grey': 248,
'red': 9,
'blue': 4,
'green': 2,
'yellow': 3,
'red_0': 198,
'blue_0': 45,
'yellow_0': 184,
'green_0': 41,
'cream': 173,
'orange': 178,
'turquoise': 51,
}
__builtin__.str = ColorizeString
@huseyin
Copy link
Author

huseyin commented Nov 14, 2015

Test kodu üretecine bir göz atalım:

def test():
    text = 'foobar'
    colors = str('').colors().keys()
    for cl in colors:
        print cl, '->' , str(text).colorize(cl)
test()

Ayrıca,

...
str(text).colorize(color=cl)
...

şeklinde de kullanılabilir.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment