I'm trying to implement colour cycling on my text in Python, ie i want it to cycle through the colour of every character typed (amongst other effects) My progress so far has been hacked together from an ansi colour recipe improvement suggestions welcomed.
I was also vaguely aware of, but never used: termcolor, colorama, curses
during the hack i managed to make the attributes not work (ie reverse blink etc) and its not perfect probably mainly because I dont understand these lines properly:
cmd.append(format % (colours[tmpword]+fgoffset))
c=format % attrs[tmpword] if tmpword in attrs else None
if anyone can clarify that a bit, I would appreciate it. this runs and does something, but its not quite there. I changed the code so instead of having to separate colour commands from your string you can include them.
#!/usr/bin/env python
'''
"arg" is a string or None
if "arg" is None : the terminal is reset to his default values.
if "arg" is a string it must contain "sep" separated values.
if args are found in globals "attrs" or "colors", or start with "#" \
they are interpreted as ANSI commands else they are output as text.
#* commands:
#x;y : go to xy
# : go to 1;1
## : clear screen and go to 1;1
#[colour] : set foreground colour
^[colour] : set background colour
examples:
echo('#red') : set red as the foreground color
echo('#red ^blue') : red on blue
echo('#red #blink') : blinking red
echo() : restore terminal default values
echo('#reverse') : swap default colors
echo('^cyan #blue reverse') : blue on cyan <=> echo('blue cyan)
echo('#red #reverse') : a way to set up the background only
echo('#red #reverse #blink') : you can specify any combinaison of \
attributes in any order with or without colors
echo('#blink Python') : output a blinking 'Python'
echo('## hello') : clear the screen and print 'hello' at 1;1
colours:
{'blue': 4, 'grey': 0, 'yellow': 3, 'green': 2, 'cyan': 6, 'magenta': 5, 'white': 7, 'red': 1}
'''
'''
Set ANSI Terminal Color and Attributes.
'''
from sys import stdout
import random
import sys
import time
esc = '%s['%chr(27)
reset = '%s0m'%esc
format = '1;%dm'
fgoffset, bgoffset = 30, 40
for k, v in dict(
attrs = 'none bold faint italic underline blink fast reverse concealed',
colours = 'grey red green yellow blue magenta cyan white'
).items(): globals()[k]=dict((s,i) for i,s in enumerate(v.split()))
bpoints = ( " [*] ", " [!] ", )
def echo(arg=None, sep=' ', end='\n', rndcase=True, txtspeed=0.03, bnum=0):
cmd, txt = [reset], []
if arg:
if bnum != 0:
sys.stdout.write(bpoints[bnum-1])
# split the line up into 'sep' seperated values - arglist
arglist=arg.split(sep)
# cycle through arglist - word seperated list
for word in arglist:
if word.startswith('#'):
### First check for a colour command next if deals with position ###
# go through each fg and bg colour
tmpword = word[1:]
if tmpword in colours:
cmd.append(format % (colours[tmpword]+fgoffset))
c=format % attrs[tmpword] if tmpword in attrs else None
if c and c not in cmd:
cmd.append(c)
stdout.write(esc.join(cmd))
continue
# positioning (starts with #)
word=word[1:]
if word=='#':
cmd.append('2J')
cmd.append('H')
stdout.write(esc.join(cmd))
continue
else:
cmd.append('%sH'%word)
stdout.write(esc.join(cmd))
continue
if word.startswith('^'):
### First check for a colour command next if deals with position ###
# go through each fg and bg colour
tmpword = word[1:]
if tmpword in colours:
cmd.append(format % (colours[tmpword]+bgoffset))
c=format % attrs[tmpword] if tmpword in attrs else None
if c and c not in cmd:
cmd.append(c)
stdout.write(esc.join(cmd))
continue
else:
for x in word:
if rndcase:
# thankyou mark!
if random.randint(0,1):
x = x.upper()
else:
x = x.lower()
stdout.write(x)
stdout.flush()
time.sleep(txtspeed)
stdout.write(' ')
time.sleep(txtspeed)
if txt and end: txt[-1]+=end
stdout.write(esc.join(cmd)+sep.join(txt))
if __name__ == '__main__':
echo('##') # clear screen
#echo('#reverse') # attrs are ahem not working
print 'default colors at 1;1 on a cleared screen'
echo('#red hello this is red')
echo('#blue this is blue #red i can ^blue change #yellow blah #cyan the colours in ^default the text string')
print
echo()
echo('default')
echo('#cyan ^blue cyan blue')
print
echo()
echo('#cyan this text has a bullet point',bnum=1)
print
echo('#yellow this yellow text has another bullet point',bnum=2)
print
echo('#blue this blue text has a bullet point and no random case',bnum=1,rndcase=False)
print
echo('#red this red text has no bullet point, no random case and no typing effect',txtspeed=0,bnum=0,rndcase=False)
# echo('#blue ^cyan blue cyan')
#echo('#red #reverse red reverse')
# echo('yellow red yellow on red 1')
# echo('yellow,red,yellow on red 2', sep=',')
# print 'yellow on red 3'
# for bg in colours:
# echo(bg.title().center(8), sep='.', end='')
# for fg in colours:
# att=[fg, bg]
# if fg==bg: att.append('blink')
# att.append(fg.center(8))
# echo(','.join(att), sep=',', end='')
#for att in attrs:
# echo('%s,%s' % (att, att.title().center(10)), sep=',', end='')
# print
from time import sleep, strftime, gmtime
colist='#grey #blue #cyan #white #cyan #blue'.split()
while True:
try:
for c in colist:
sleep(.1)
echo('%s #28;33 hit ctrl-c to quit' % c,txtspeed=0)
echo('%s #29;33 hit ctrl-c to quit' % c,rndcase=False,txtspeed=0)
#echo('#yellow #6;66 %s' % strftime('%H:%M:%S', gmtime()))
except KeyboardInterrupt:
break
except:
raise
echo('#10;1')
print
should also mention that i have absolutely no idea what this line does :) - well i see that it puts colours into a dictionary object, but how it does it is confusing. not used to this python syntax yet.
for k, v in dict(
attrs = 'none bold faint italic underline blink fast reverse concealed',
colours = 'grey red green yellow blue magenta cyan white'
).items(): globals()[k]=dict((s,i) for i,s in enumerate(v.split()))
This is a rather convoluted code - but, sticking to you r question, about the lines:
cmd.append(format % (colours[tmpword]+fgoffset))
This expression appends to the list named cmd the interpolation of the string contained in the variable format with the result of the expression (colours[tmpword]+fgoffset))- which concatenates the code in the color table (colours) named by tmpword with fgoffset.
The format string contains '1;%dm' which means it expects an integer number, whcih will replace the "%d" inside it. (Python's % string substitution inherits from C's printf formatting) . You "colours" color table ont he other hand is built in a convoluted way I'd recomend in no code, setting directly the entry in "globals" for it - but let's assume it does have the correct numeric value for each color entry. In that case, adding it to fgoffset will generate color codes out of range (IRCC, above 15) for some color codes and offsets.
Now the second line in which you are in doubt:
c=format % attrs[tmpword] if tmpword in attrs else None
This if is just Python's ternary operator - equivalent to the C'ish expr?:val1: val2
It is equivalent to:
if tmpword in attrs:
c = format % attrs[tmpword]
else:
c = format % None
Note that it has less precedence than the % operator.
Maybe you would prefer:
c= (format % attrs[tmpword]) if tmpword in attrs else ''
instead
Related
I am trying to iterate through a little array and create urls out of the information contained therein.
Here's a dummy setup of what I'm trying to do:
import urllib.parse
DEEP_CAT_URL = 'https://google.com/search?q=%s'
def GetCatLink(cats=()):
for cat in cats:
cat_id = cat['name']
color = cat.get('color')
if color:
deep_cat_url = DEEP_CAT_URL % urllib.parse.quote(color+'+cat',safe='+')
return (deep_cat_url)
CATS = [
{
'color': 'red',
'name': 'Redd Foxx',
},
{
'color': 'black',
'name': 'Donnie Darko',
},
]
print("There are "+str(len(CATS))+" cats to consider")
for h in range(len(CATS)):
cnum=str(h+1)
print("Cat #"+cnum+":")
if CATS[h]["color"] != '':
print("The name of Cat #{} is {}. The color of {} is {}.".format(cnum,CATS[h]["name"],CATS[h]["name"], CATS[h]["color"]))
x=CATS[h]
print(x)
print(GetCatLink(CATS))
It kind of works, but outputs:
There are 2 cats to consider
Cat #1:
The name of Cat #1 is Redd Foxx. The color of Redd Foxx is red.
{'color': 'red', 'name': 'Redd Foxx'}
https://google.com/search?q=red+cat
Cat #2:
The name of Cat #2 is Donnie Darko. The color of Donnie Darko is black.
{'color': 'black', 'name': 'Donnie Darko'}
https://google.com/search?q=red+cat
The goal here is to have two urls:
Cat#1 https://google.com/search?q=red+cat
Cat#2 https://google.com/search?q=black+cat
You're looping over all cats in GetCatLink and on the first iteration, you return a URL - so you always get the URL for the first cat in CATS. There's no reason to do any looping over there, why not pass the cat you want a URL for to the function and just process that one?
Instead of:
def GetCatLink(cats=()):
for cat in cats:
cat_id = cat['name']
color = cat.get('color')
if color:
deep_cat_url = DEEP_CAT_URL % urllib.parse.quote(color+'+cat',safe='+')
return (deep_cat_url)
Use:
def get_cat_link(cat):
cat_id = cat['name']
color = cat.get('color')
return DEEP_CAT_URL % urllib.parse.quote(color + '+cat', safe='+')
And instead of this:
print(GetCatLink(CATS))
This:
print(get_cat_link(x))
There's more to be said about your code - there's some surplus stuff in there, but this addresses your main issue.
(As #JonClements correctly comments: you will run into trouble if you try make requests with the URLs you're creating, unless you use them in a normal browser. Google won't give you the result you expect if you just use urllib or requests without getting "tricksy".)
The function GetCatLink and its invocation needs to be modified. Then everything works well.
def GetCatLink(cat):
color = cat.get('color')
if color:
return DEEP_CAT_URL % urllib.parse.quote(color + '+cat', safe='+')
for h in range(len(CATS)):
cnum = str(h + 1)
print("Cat #" + cnum + ":")
if CATS[h]["color"] != '':
print("The name of Cat #{} is {}. The color of {} is {}.".format(cnum, CATS[h]["name"], CATS[h]["name"],
CATS[h]["color"]))
x = CATS[h]
print(x)
print(GetCatLink(CATS[h]))
I have a long string, and I've extracted the substrings I wanted. I am looking for a method which uses less lines of code to get my output. I'm after all the sub strings which start with CN=., and removing everything else up-to the semi-colon..
example list output (see picture)
The script I'm currently using is below
import re
import fnmatch
import os
# System call
os.system("")
# Class of different styles
class style():
BLACK = '\033[30m'
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
MAGENTA = '\033[35m'
CYAN = '\033[36m'
WHITE = '\033[37m'
UNDERLINE = '\033[4m'
RESET = '\033[0m'
CNString = "CN=User2,OU=blurb,OU=Test,DC=Test,DC=Testal;CN=User4,OU=blurb,OU=Test,DC=Test,DC=Testal;CN=User56,OU=blurb,OU=Test,DC=Test,DC=Testal;CN=User9,OU=blurb,OU=Test,DC=Test,DC=Testal;CN=Jane45 user,OU=blurb,OU=Test,DC=Test,DC=Testal;CN=User-Donna,OU=blurb,OU=Test,DC=Test,DC=Testal;CN=User76 smith,OU=blurb,OU=Test4,DC=Test,DC=Testal;CN=Pink Panther,OU=blurb,OU=Test,DC=Testing,DC=Testal;CN=Testuser78,OU=blurb,OU=Tester,DC=Test,DC=Testal;CN=great Scott,OU=blurb,OU=Test,DC=Test,DC=Local;CN=Leah Human,OU=blurb,OU=Test,DC=Test,DC=Testal;CN=Alan Desai,OU=blurb,OU=Test,DC=Test,DC=Testal;CN=Duff Beer,OU=Groups,OU=Test,DC=Test,DC=Testal;CN=Jane Doe,OU=Users,OU=Test76,DC=Test,DC=Testal;CN=simple user67,OU=Users,OU=Test,DC=Test,DC=Testal;CN=test O'Lord,OU=Users,OU=Test,DC=Concero,DC=Testal"
newstring1 = CNString.replace(';','];')
print(newstring1)
newstring2 = newstring1.replace(',OU=',',[OU=')
print(newstring2)
newstring3 = newstring2.replace(',[OU','],[OU')
print(newstring3)
newstring4 = newstring3.replace('],[OU',',[OU')
print(newstring4)
newstring5 = newstring4.replace('];',']];')
print(newstring5)
endstring = "]]"
newstring6 = newstring5 + endstring
print(newstring6)
newstring7 = re.sub("\[.*?\]","()",newstring6)
print(newstring7)
print(style.YELLOW + "Line Break")
newstring8 = newstring7.replace(',()]','')
print(style.RESET + newstring8)
newstring9 = newstring8.split(';')
for cnname in newstring9:
print(style.GREEN + cnname)
Not sure why your code is juggling with those square brackets. Wouldn't this do it?
names = re.findall(r"\bCN=[^,;]*", CNString)
cn_list = [elem.split(",")[0] for elem in CNString.split(";") if elem.startswith("CN=")]
If I print cn_list I obtain:
['CN=User2', 'CN=User4', 'CN=User56', 'CN=User9', 'CN=Jane45 user', 'CN=User-Donna', 'CN=User76 smith', 'CN=Pink Panther', 'CN=Testuser78', 'CN=great Scott', 'CN=Leah Human', 'CN=Alan Desai', 'CN=Duff Beer', 'CN=Jane Doe', 'CN=simple user67', "CN=test O'Lord"]
I want to get the color of the text for each text field in the PPT.
Is it possible to do with Python-pptx?
I'm trying using the below code to check if the text is green color and print Yes but it always prints No.
file = Presentation('file_name.pptx')
for slide in file.slides:
for shape in slide.shapes:
if hasattr(shape, "text"):
tf = shape.text_frame
p = tf.paragraphs[0]
if p.font.color == RGBColor(0, 255, 0):
print("Yes")
else:
print("No")
I need a wordcloud in which the same word could appear twice with different colors; red indicating negative associations, and green positive.
I am already able to generate a wordcloud with repeated words using MultiDicts (see the code below):
However, I need one of the homes to appear in green color. Is this possible with the wordcloud libray? Can somebody recommend another library that support this?
from wordcloud import WordCloud
from multidict import MultiDict
class WordClouder(object):
def __init__(self, words, colors):
self.words = words
self.colors = colors
def get_color_func(self, word, **args):
return self.colors[word]
def makeImage(self, path):
wc = WordCloud(background_color="white", width=200, height=100)
# generate word cloud
wc.generate_from_frequencies(self.words)
# color the wordclound
wc.recolor(color_func=self.get_color_func)
image = wc.to_image()
image.save(path)
if __name__ == '__main__':
# Ideally this would be used somewhere
colors_valence = {
'+': 'green',
'-': 'red',
}
colors = {
'home': 'red',
'car': 'green',
}
words = MultiDict({
'home': 2.0, # This home should be green
'car': 20.0,
})
words.add('home',10) , # This home should be red
wc = WordClouder(words, colors)
wc.makeImage('wordcloud.png')
I created a decent solution by inherit from WordCloud. You can just copy and paste the code below, and then you can use + and - to indicate the color, something like this:
words = {
'home+': 2.0,
'home-': 10.0,
'car+': 5.0,
}
would generate this:
Explanation: I added a character after the word in the dictionary that tells me the color (+ or -). I removed the character in the recolor method of the WordCloud that I overwrote, but I did send the entire world (including the character + or -) to the color_fun that I use to select the appropriate color. I commented the important bits in the code below.
from wordcloud import WordCloud as WC
from multidict import MultiDict
class WordCloud(WC):
def recolor(self, random_state=None, color_func=None, colormap=None):
if isinstance(random_state, int):
random_state = Random(random_state)
self._check_generated()
if color_func is None:
if colormap is None:
color_func = self.color_func
else:
color_func = colormap_color_func(colormap)
# Here I remove the character so it doesn't get displayed
# when the wordcloud image is produced
self.layout_ = [((word_freq[0][:-1], word_freq[1]), font_size, position, orientation,
# but I send the full word to the color_func
color_func(word=word_freq[0], font_size=font_size,
position=position, orientation=orientation,
random_state=random_state,
font_path=self.font_path))
for word_freq, font_size, position, orientation, _
in self.layout_]
return self
class WordClouder(object):
def __init__(self, words, colors):
self.words = words
self.colors = colors
def get_color_func(self, word, **args):
return self.colors[word[-1]]
def makeImage(self, path):
#alice_mask = np.array(Image.open("alice_mask.png"))
wc = WordCloud(background_color="white", width=200, height=100)
# generate word cloud
wc.generate_from_frequencies(self.words)
# color the wordclound
wc.recolor(color_func=self.get_color_func)
image = wc.to_image()
image.save(path)
if __name__ == '__main__':
colors = {
'+': '#00ff00',
'-': '#ff0000',
}
words = {
'home+': 2.0,
'home-': 10.0,
'car+': 5.,
}
wc = WordClouder(words, colors)
wc.makeImage('wc.png')
I make 2 python files: MineSweeping.py and CmdColor.py
And in MineSweeping.py I want to call a func defined in CmdColor.py to make the shell with color output, but failed.
The code of CmdColor.py is below:
#!/usr/bin/env python
#encoding: utf-8
import ctypes
STD_INPUT_HANDLE = -10
STD_OUTPUT_HANDLE= -11
STD_ERROR_HANDLE = -12
FOREGROUND_BLACK = 0x0
FOREGROUND_BLUE = 0x01 # text color contains blue.
FOREGROUND_GREEN= 0x02 # text color contains green.
FOREGROUND_RED = 0x04 # text color contains red.
FOREGROUND_INTENSITY = 0x08 # text color is intensified.
BACKGROUND_BLUE = 0x10 # background color contains blue.
BACKGROUND_GREEN= 0x20 # background color contains green.
BACKGROUND_RED = 0x40 # background color contains red.
BACKGROUND_INTENSITY = 0x80 # background color is intensified.
class Color:
std_out_handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
def set_cmd_color(self, color, handle=std_out_handle):
"""(color) -> bit
Example: set_cmd_color(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY)
"""
bool = ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color)
return bool
def reset_color(self):
self.set_cmd_color(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE)
def print_red_text(self, print_text):
self.set_cmd_color(FOREGROUND_RED | FOREGROUND_INTENSITY)
print print_text
self.reset_color()
if __name__ == "__main__":
clr = Color()
clr.print_red_text('red')
clr.print_green_text('green')
clr.print_blue_text('blue')
clr.print_red_text_with_blue_bg('background')
And in MineSweeping.py I do so to call the func:
import CmdColor
...
clr = CmdColor.Color()
clr.print_red_text('red')
But the output string 'red' is white
If I merge the CmdColor.py into abc.py, then it can output a red string of 'red'.
The code can be found here:
https://github.com/tomxuetoy/Python_MineSweeping
Why?
Thanks!