How to use dictionary from other funtion to another - python

Im a beginner and please help, what exactly i need to use to next one:
i want to use dictionary data with name & color from init_dict to show_dict and print it all
from printing_functions_1 import init_dict as pr
from printing_functions_1 import show_dict as sd
pr('DArya', 'Total Black', another_color = 'purple', lovely_film = 'mystic')
sd(another_color = 'purple', lovely_film = 'mystic')
def init_dict(name, color, **argv):
argv['Name'] = name
argv['Color'] = color
def show_dict(**argv):
for key, value in argv.items():
print(key, value)
expect somethinglike this from output with show_dict:
another_color purple
lovely_film mystic
Name DArya
Color Total Black

Related

Python Pandas: How to change cell font and background color

I want to alter the font and background color of the cell based on the conditions, but my script now just changes the background/cell color. Is there a way I could make the text and cell the same color? I'm not familiar with style.applymap yet so please bear with me.
import pandas as pd
import pypyodbc as odbc
def color(val):
if val == 0:
color = 'red'
elif val == 1:
color = 'green'
elif val == 3:
color = 'blue'
return f'background-color: {color}; color: {color}'
conn = odbc.connect(MyConn)
rd = pd.read_sql("SELECT * FROM TABLE", conn)
rdx = pd.pivot_table(rd, index = ['LIST'] ,columns='month', values='status',aggfunc='sum' )
rdx = rdx.style.applymap(color)
You can mapping values in dictionary if match else return empty string:
df = pd.DataFrame({'a':[2,0,1,3],'b':[3,0,1,3]})
def color(val):
d = {0:'red', 1: 'green', 3:'blue'}
return f'background-color: {d[val]}; color: {d[val]}' if val in d else ''
df.style.applymap(color)

How does one iterate through an array to make different urls?

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]))

Regex through line of text with changing pattern

Expanding on Proper way to search through line of text, re.findall() and re.search() both don't fully work
If I have the following line of text:
txt = "Name : 'red' Wire : 'R' Wire: 'B' Name : 'blue' Name : 'orange' Name: 'yellow' Wire : 'Y'"
I am trying to parse through this line of text and get every Wire/Name pair to populate into a dataframe. The issue with this text is that the order Wire/Name on the line of text is variable.
for line in txt:
line = line.strip()
pairs = re.findall(r'Name *: *\'(?P<name>\w+)\' Wire *: *\'(?P<wire>\w+)\'', content)
if pairs:
for name, wire in pairs:
df = df.append({'Name' : name, 'Wire' : wire}, ignore_index=True)
The problem with this approach is that it misses the Blue/B pair, resulting in the following dataframe.
Name Wire
red R
yellow Y
The dataframe I am trying to achieve is
Name Wire
red R
blue B
yellow Y
Is it possible to handle the variation in the text pattern?
Can you just take one name/wire pair at a time and build up the pieces as you go? I created a Pair class with some helper functions:
txt = "Name : 'red' Wire : 'R' Wire: 'B' Name : 'blue' Name : 'orange' Name: 'yellow' Wire : 'Y'"
regex = r'((?P<name>Name)|(?P<wire>Wire))\s*?:\s*?\'(?P<value>\w+\')'
pat = re.compile(regex)
class Pair:
name = ''
wire = ''
def populated(self):
return self.name and self.wire
def to_dict(self):
return dict(name=self.name, wire=self.wire)
def __str__(self):
return f'{self.name} {self.wire}'
current_pair = Pair()
all_pairs = []
for x in pat.finditer(txt):
if x.group('name'):
current_pair.name = x.group('value')
elif x.group('wire'):
current_pair.wire = x.group('value')
if current_pair.populated():
all_pairs.append(current_pair)
current_pair = Pair()
for p in all_pairs:
print(p)
You could alter this code to keep track of the incomplete pairs (i.e. 'orange') and decide what to do with those later.

How to create a wordcloud with the same word several times but with different colors?

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')

colour terminal text effects with Python

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

Categories