I was browsing the Django source code and I saw this function:
def colorize(text='', opts=(), **kwargs):
"""
Returns your text, enclosed in ANSI graphics codes.
Depends on the keyword arguments 'fg' and 'bg', and the contents of
the opts tuple/list.
Returns the RESET code if no parameters are given.
Valid colors:
'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'
Valid options:
'bold'
'underscore'
'blink'
'reverse'
'conceal'
'noreset' - string will not be auto-terminated with the RESET code
Examples:
colorize('hello', fg='red', bg='blue', opts=('blink',))
colorize()
colorize('goodbye', opts=('underscore',))
print colorize('first line', fg='red', opts=('noreset',))
print 'this should be red too'
print colorize('and so should this')
print 'this should not be red'
"""
code_list = []
if text == '' and len(opts) == 1 and opts[0] == 'reset':
return '\x1b[%sm' % RESET
for k, v in kwargs.iteritems():
if k == 'fg':
code_list.append(foreground[v])
elif k == 'bg':
code_list.append(background[v])
for o in opts:
if o in opt_dict:
code_list.append(opt_dict[o])
if 'noreset' not in opts:
text = text + '\x1b[%sm' % RESET
return ('\x1b[%sm' % ';'.join(code_list)) + text
I removed it out of the context and placed in another file just to try it, the thing is that it doesn't seem to colour the text I pass it. It might be that I don't understand it correctly but isn't it supposed to just return the text surrounded with ANSI graphics codes which than the terminal will convert to actual colours.
I tried all the given examples of calling it, but it just returned the argument I specified as a text.
I'm using Ubuntu so I think the terminal should support colours.
It's that you have many terms undefined, because it relies on several variables defined outside of the function.
Instead just
import django.utils.termcolors as termcolors
red_hello = termcolors.colorize("Hello", fg='red') # '\x1b[31mHello\x1b[0m'
print red_hello
Or just also copy the first few lines of django/utils/termcolors.py specifically:
color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white')
foreground = dict([(color_names[x], '3%s' % x) for x in range(8)])
background = dict([(color_names[x], '4%s' % x) for x in range(8)])
RESET = '0'
def colorize( ... ):
...
print colorize("Hello", fg='red') # '\x1b[31mHello\x1b[0m'
Also note:
>>> from django.utils.termcolors import colorize
>>> red_hello = colorize("Hello", fg="red")
>>> red_hello # by not printing; it will not appear red; special characters are escaped
'\x1b[31mHello\x1b[0m'
>>> print red_hello # by print it will appear red; special characters are not escaped
Hello
Related
I have a large list of Unicode icons that I want to display. However, I would like to hide/skip any icon that I cannot display (because I don't have the correct font installed). Is there a programmatic way to determine this?
There's nothing built into Python for this. However, you can apply the fonttools module e.g. as follows (used in Windows 10):
# ToDo: find fallback font
# ToDo: reverse algorithm (font => characters) instead of (character => fonts)
# ToDo: check/print merely basic font (omit variants like Bold, Light, Condensed, β¦)
import unicodedata
import sys
import os
from fontTools.ttLib import TTFont, TTCollection
fontsPaths = []
fontcPaths = []
fontsdirs = [ os.path.join( os.getenv('SystemRoot'), 'Fonts') # r"c:\Windows\Fonts"
, r"D:\Downloads\MathJax-TeX-fonts-otf"
# , os.path.join( os.getenv('LOCALAPPDATA'), r'Microsoft\Windows\Fonts')
]
print(fontsdirs, file=sys.stderr)
for fontsdir in fontsdirs:
for root,dirs,files in os.walk( fontsdir ):
for file in files:
if file.endswith(".ttf") or file.endswith(".otf") or file.endswith(".ttc"):
tfile = os.path.join(root,file)
if file.endswith(".ttc"):
fontcPaths.append(tfile)
else:
fontsPaths.append(tfile)
# print( len(fonts), "fonts", fontsdir)
def char_in_font(unicode_char, font):
for cmap in font['cmap'].tables:
if cmap.isUnicode() or cmap.getEncoding() == 'utf_16_be':
if ord(unicode_char) in cmap.cmap:
# print(type(cmap))
auxcn = cmap.cmap[ord(unicode_char)]
# print(auxcn, type(auxcn))
return auxcn if auxcn != '' else '<nil>'
return ''
def checkfont(char,font,fontdict,fontpath):
nameID_index = 1 # works generally (not always)
for i,f in enumerate(font['name'].names):
# An Introduction to TrueType Fonts: A look inside the TTF format
# https://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=IWS-Chapter08
# 1 = Font Family name, 2 = Font SubFamily name, 4 = Full font name
if f.nameID == 1:
nameID_index = i
break
fontname = font['name'].names[nameID_index].toStr()
if fontname not in fontdict.keys():
aux = char_in_font(char, font)
if aux != '':
fontdict[fontname] = "{} ({}) [{}] '{}' \t {} {}".format(
char,
'0x{:04x}'.format(ord(char)),
aux,
fontname, # string.decode('unicode-escape'),
# '', ''
'in', fontpath.split('\\')[-1]
)
def testfont(char):
fontdict = {}
for fontpath in fontsPaths:
font = TTFont(fontpath) # specify the path to the font
checkfont(char,font,fontdict,fontpath)
for fontpath in fontcPaths: # specify the path to the font collection
fonts = TTCollection(fontpath)
for ii in range(len(fonts)):
font = TTFont(fontpath, fontNumber=ii) # fontfile and index
checkfont(char,font,fontdict,fontpath)
return fontdict.values()
def testprint(char):
print('') # empty line for better readability
print(char, ' 0x{:04x}'.format(ord(char)), unicodedata.name(char, '???'))
fontarray = testfont(char)
for x in fontarray:
print(x)
if len(sys.argv) == 1:
# sample output
testprint(u"ΰ€
") # 0x0905 Devanagari Letter A
else:
for i in range( 1, len(sys.argv) ):
if len(sys.argv[i]) >=2:
try:
chars = chr(int(sys.argv[i])) # 0x042F or 1071
except:
try:
chars = chr(int(sys.argv[i],16)) # 042F
except:
chars = (sys.argv[i].
encode('raw_unicode_escape').
decode('unicode_escape')) # βπ\U00010A30\u042F\xFE
else:
chars = sys.argv[i] # Π― (Cyrillic Capital Letter Ya)
for char in chars:
testprint(char);
Sample output (if called without arguments): .\FontGlyphs.py
['C:\\WINDOWS\\Fonts', 'D:\\Downloads\\MathJax-TeX-fonts-otf']
ΰ€
0x0905 DEVANAGARI LETTER A
ΰ€
(0x0905) [uni0905] 'Nirmala UI' in Nirmala.ttf
ΰ€
(0x0905) [uni0905] 'Nirmala UI Semilight' in NirmalaS.ttf
ΰ€
(0x0905) [uni0905] 'Unifont' in unifont-8.0.01.ttf
ΰ€
(0x0905) [uni0905] 'Unifont CSUR' in unifont_csur-8.0.01.ttf
Another example: .\FontGlyphs.py π
['C:\\WINDOWS\\Fonts', 'D:\\Downloads\\MathJax-TeX-fonts-otf']
π 0x1f408 CAT
π (0x1f408) [u1F408] 'EmojiOne Color' in EmojiOneColor-SVGinOT.ttf
π (0x1f408) [u1F408] 'Segoe UI Emoji' in seguiemj.ttf
π (0x1f408) [u1F408] 'Segoe UI Symbol' in seguisym.ttf
FYI, I have written similar script that shows output (glyphs) rendered using appropriate fonts (using default browserβ¦
Limitation the script does not recognize Emoji Sequence, for instance
.\FontGlyphs.py ππ½
['C:\\WINDOWS\\Fonts', 'D:\\Downloads\\MathJax-TeX-fonts-otf']
π 0x1f44d THUMBS UP SIGN
π (0x1f44d) [u1F44D] 'EmojiOne Color' in EmojiOneColor-SVGinOT.ttf
π (0x1f44d) [u1F44D] 'Segoe UI Emoji' in seguiemj.ttf
π (0x1f44d) [u1F44D] 'Segoe UI Symbol' in seguisym.ttf
π½ 0x1f3fd EMOJI MODIFIER FITZPATRICK TYPE-4
π½ (0x1f3fd) [u1F3FD] 'EmojiOne Color' in EmojiOneColor-SVGinOT.ttf
π½ (0x1f3fd) [u1F3FD] 'Segoe UI Emoji' in seguiemj.ttf
π½ (0x1f3fd) [u1F3FD] 'Segoe UI Symbol' in seguisym.ttf
You can use pywin32 to check for the required fonts.
import win32gui
def fontFamProc(font, tm, fonttype, names):
names.append(font.lfFaceName)
return True
fonts = []
deviceContext = win32gui.GetDC(None)
win32gui.EnumFontFamilies(deviceContext, None, fontFamProc, fonts)
win32gui.ReleaseDC(deviceContext, None)
print(fonts)
Well, you could simply print all of Unicode and find out that way. E.g., (I can print most all if not all :
import io
with io.open("all_utf-8.txt", "w", encoding="utf8") as f:
for n in range(150000):
try:
i = chr(n)
if i.isprintable():
print(f"{i}", end="", file=f)
if n % 200 == 0:
print(file=f)
except UnicodeError:
pass
(note the use of the built-in Python str method isprintable())
& here's a bit of a zoom in so you can actually see the individual chars/glyphs... π
As you can tell in the picture below, the table is separated by characters rather than full words.
def apply(f):
text = f
text = re.sub(r'\W+', ' ', text)
res = LM().check_probabilities(text, topk=20)
l = str(res)
paraphrase_widget = widgets.SelectMultiple(
options=l,
description='Paraphrases',
disabled=False,
layout= widgets.Layout(width='100%')
)
display(paraphrase_widget)
return {"result": res}
apply("In order to")
The issue here is in unpacking pytorch's prediction and passing those results to the widget in proper format (a list of tuples). Here's how you can do that:
# Modify your widget to the following
paraphrase_widget = widgets.SelectMultiple(
options=res['pred_topk'][2],
description='Paraphrases',
disabled=False,
layout= widgets.Layout(width='100%', height="300px")
)
Here's what this looks like for me:
I need to simplify this list of numbers but have it so that it also includes a certain letter, how can I simplify my list?
Right now I've already made the list however I need some code which randomly chooses a certain number out of this list.
carddeck = ['r01', 'r02', 'r03', 'r04', 'r05', 'r06', 'r07', 'r08', 'r09', 'r10', 'b01', 'b02', 'b03', 'b04', 'b05', 'b06', 'b07', 'b08', 'b09', 'b10', 'y01', 'y02', 'y03', 'y04', 'y05', 'y06', 'y07', 'y08','y09', 'y10']
colours = ['red', 'black', 'yellow']
validOptionsR = ['r01', 'r02', 'r03', 'r04', 'r05', 'r06', 'r07', 'r08', 'r09', 'r10']
validOptionsB = ['b01', 'b02', 'b03', 'b04', 'b05', 'b06', 'b07', 'b08', 'b09', 'b10']
validOptionsY = ['y01', 'y02', 'y03', 'y04', 'y05', 'y06', 'y07', 'y08','y09', 'y10']
I'd like a code which doesn't use the full list but instead picks a random number from 01 to 10 and put it alongside the chosen colour, for example, a black card would be b09. here is the rest of my code:
rndClr = random.choice(colours)
if rndClr.find('black'):
rndClr = 'black'
print('black')
elif rndClr.find('yellow'):
rndClr = 'yellow'
print('yellow')
elif rndClr.find('red'):
rndClr = 'red'
print('red')
else:
print('An Error Has Occurred While Calculating the Card Colour')
def colourPicker():
colourWind = Tk()
colourWind.title('Cards')
colourWind.configure(bg = rndClr)
def playerCardPick():
if rndClr == 'red' :
random.shuffle(validOptionsR)
chosencard = random.choice(validOptionsR)
elif rndClr == 'black' :
random.shuffle(validOptionsB)
chosencard = random.choice(validOptionsB)
else:
random.shuffle(validOptionsY)
chosencard = random.choice(validOptionsY)
print(str(chosencard))
You can do this with
print(rndColor[0] + str(random.randint(1, 11)))
It takes the first letter of your color and prepends it to a random number between 1 and 10.
Also, the if-else-if ladder can be condensed to
if rndColor not in color:
print("Error message here")
exit()
But I don't think that rndColor will take any value not in the list. Not sure though
This is my first python program and my first asking a question on stack overflow so I apologize if my code is a mess and or if my question is ill-formatted.
I would like to print the same line I'm already printing, but each float should be a different color based on its value. (specifically >.7 is green, .7< is red) What is the best way to do this?
oreName=[#string names]
#escape char? I know there has to be a better way than this
#but this is the best ive come up with as the escape char didnt
#work the way I thought it should for '%'
char = '%'
netProfitBroker=[
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0]]
##code that populates netProfitBroker
def printOutput(array):
"this prints all of the lines"
for i in range(0,10):
print oreName[i]+"= %.3f \t 5"%(array[0][i])+char+"=%.3f \t10"%(array[1][i])+char+"=%.3f"%(array[2][i])
print "\nnet profit brokered"
printOutput(netProfitBroker)
the output looks a bit like this: (I lost some/all of my whitespace formatting when I copied the output here)
net profit brokered
Veldspar = 0.234 5%=0.340 10%=-0.017
Scordite = 0.752 5%=0.297 10%=0.259
Pyroxeres = 0.406 5%=1.612 10%=2.483
Plagioclase= 1.078 5%=0.103 10%=1.780
Omber = -7.120 5%=5.416 10%=4.612
Kernite = -10.822 5%=15.366 10%=6.626
Jaspet = 17.772 5%=49.278 10%=62.380
Hemorphite = -35.431 5%=82.912 10%=141.027
Gneiss = 8.086 5%=-4638.549 10%=-3610.570
Arkonor = 349.867 5%=-545.284 10%=-340.298
essentially:
"ore name=" arrayVal1 "5%="arrayVal2 "10%="arrayVal3
All the array vals should be printed out to 3 decimal places.
You can use ASCII color codes at the beginning of your print to change the color, as an example '\033[91m' for RED and '\033[94m' for BLUE.
e.g
if array[0][i] > 7:
print '\033[94m' + oreName[i]+"= %.3f \t 5"%(array[0][i])
elif array[0][i] < 7:
print '\033[91m' + oreName[i]+"= %.3f \t 5"%(array[0][i])
You can read about ASCII escape codes here.
Edit: Added additional example code.
Here is a list of some common colors you can use:
Red = '\033[91m'
Green = '\033[92m'
Blue = '\033[94m'
Cyan = '\033[96m'
White = '\033[97m'
Yellow = '\033[93m'
Magenta = '\033[95m'
Grey = '\033[90m'
Black = '\033[90m'
Default = '\033[99m'
Additionally as mentioned in the comment. You can chain these to get different colors on the same line.
print '\033[91m' + 'Red' + "\033[99m" + 'Normal' + '\033[94m' + 'Blue
You could even do a function.
# Store a dictionary of colors.
COLOR = {
'blue': '\033[94m',
'default': '\033[99m',
'grey': '\033[90m',
'yellow': '\033[93m',
'black': '\033[90m',
'cyan': '\033[96m',
'green': '\033[92m',
'magenta': '\033[95m',
'white': '\033[97m',
'red': '\033[91m'
}
def print_with_color(message, color='red'):
print(COLOR.get(color.lower(), COLOR['default']) + message)
print_with_color('hello colorful world!', 'magenta')
print_with_color('hello colorful world!', 'blue')
for Easy copy-paste after print:
for style in range(8):
for fg in range(30,38):
s1 = ''
for bg in range(40,48):
myform = ';'.join([str(style), str(fg), str(bg)])
skel = '\x1b[{};{};{}m'.format(myform.split(';')[0],myform.split(';')[1],myform.split(';')[2])
s1 += f'\x1b[{myform}m {repr(skel)} \x1b[0m'
print(s1)
print('\n')
This code print multiple pretty lines with different colors. example:
'\x1b[5;31;40m' '\x1b[5;31;41m' '\x1b[5;31;42m' '\x1b[5;31;43m' for easy copy-paste to code.
After print add to you code:
mycolor = '\x1b[5;35;43m'
rest = '\x1b[0m'
and print for preview:
print(f"{mycolor}Hello world!{rest}")
for preview:
Stack attach
What's the easiest way to produce a visualization of Mercurial revision tree using Python (ideally, Python 3)?
I am guessing it would have to be through a combination 2 libraries: one that provides an interface to the Mercurial repository, and one that visualizes graphs.
Use case: we have written a (pure Python) continuous integration testing module. We'd like it to display the revision tree, marking each node as "passed", "failed", "in progress", "not tested" or something along these lines.
For the visualization part, I would check out NetworkX. It is a Python library that lets you do graph/network processing, import/export, and visualization.
Here, have my script:
#!/usr/bin/env python
from itertools import chain
import hglib
#from pygraphviz import *
repo = hglib.open('.')
log = dict((t[0], t) for t in repo.log())
def graph(): return dict((v, []) for v in log)
forward, backward, jump = (graph() for i in range(3))
for target in log:
for parent in repo.parents(target) or []:
source = parent[0]
forward[source].append(target)
backward[target].append(source)
def endpoint(v):
if len(forward[v]) != 1: return True
if len(backward[forward[v][0]]) != 1: return True
if len(backward[v]) != 1: return True
if len(forward[backward[v][0]]) != 1: return True
for v in forward:
if endpoint(v):
w = v
while len(forward[w]) == 1 == len(backward[forward[w][0]]):
w = forward[w][0]
jump[v] = w
else: del jump[v]
def vertex(tupl): return 'v' + tupl[1][:5]
print 'digraph {'
colors = ['red', 'green', 'blue', 'yellow', 'cyan', 'magenta',
'orange', 'chartreuse']
authors = dict()
for v in sorted(forward, key=int):
if not endpoint(v) or v not in jump: continue
node = 'v%s' % v
if jump[v] != v:
sep = '+' if forward[v] == jump[v] else '::'
label = '%s%s%s' % (v, sep, jump[v])
assert int(jump[v]) > int(v)
v = jump[v]
del jump[v]
else:
label = v
author = log[v][4]
print '// %s' % author
if author not in authors: authors[author] = colors[len(authors) %
len(colors)]
attrs = dict(color=authors[author], label=label, style='bold').items()
print '\t%s [%s]' % (node, ','.join('%s="%s"' % kv for kv in attrs))
for w in forward[v]: print '\t%s -> v%s' % (node, w)
print '}'
As you can tell, I use hglib to get at the Mercurial data (hglib.open('.').log() is a list of tuples, one per commit). I use graphviz for visualization. No library, I just *print* the damn thing ;-)
I run the script plus graphviz like this:
python version-dag.py > log.dot ; dot -Tpdf log.dot -o log.pdf
... and then look at the glorious .pdf file. Graphviz can do png, eps and perhaps other formats. The jump dictionary is for compression single-parent-paths down to a single node. Enjoy :)