I want to implement a for loop in the Tkinter tkMessageBox.showinfo() in python
I need to print a list of lists in the box.
What I currently have is:
tkMessageBox.showinfo(
"Help INFORMATION",
"help1 help2 \n help3 help4 \n help5 help6"
)
What I want is:
Something like below..
my_list=[['help1','help2'],['help3','help4'],['help5','help6']]
tkMessageBox.showinfo(
"Help INFORMATION",
for i in my_list:
i + "\n" #cant use print as I want to display it in the dialog box and not in the console.
)
So that the output in the dialog box should be like this :
help1 help2
help3 help4
help5 help6
But what I get is:
Syntax Error -> for i in my_list:
How about this:
my_list=[['help1','help2'],['help3','help4'],['help5','help6']]
tkMessageBox.showinfo(
"Help INFORMATION",
'\n'.join(map(' '.join, my_list))
)
I did not test it but should ideally do the job.
ok you can try this , I know it's not the most efficient one but it works !
my_list=[['help1','help2'],['help3','help4'],['help5','help6']]
def to_tuples(list):
tuples = []
for sublist in list :
tuples.append(tuple(sublist))
return tuples
def dialog_info(tuples):
res = ""
for element in tuples :
res += ' '.join(element)
res += '\n'
return res
print dialog_info(my_list)
now you can just use :
my_list = [['help1', 'help2'], ['help3', 'help4'], ['help5', 'help6']]
tkMessageBox.showinfo(
"Help INFORMATION",
dialog_info(my_list)
)
You can use
'\n'.join(map(' '.join, my_list))
instead of the for loop.
Related
I have a command that takes few non-positional arguments for example
send_dm -u def750 -n 15 -msg Hello world!
It takes whole list and indexes arguments
('-u', 'def750', '-n', '1', '-msg', 'Hello', 'world!')
def750 1 "Hello
Using this code:
allowed_args = ["-u", "-n", "-msg"]
index = args.index("-u") + 1
u = str(args[index])
index = args.index("-n") + 1
n = str(args[index])
index = args.index("-msg") + 1
msg = str(args[index])
I need to take -msg argument from its start to
Start of new argument
End of argument list
So if I do something like this
send_dm -msg Hello world! -u def750 -n 15
I'll still get:
def750 1 Hello World!
Right now only thing I'm getting is first element after -msg argument and I have no idea how to do it
Maybe try looking for the - at the beginning of each parameter
allowed_args = ["-u", "-n", "-msg"]
argumentDict = {
"-u": "",
"-n": "",
"-msg": ""
}
currentArgument = ""
for argument in args:
if argument.startswith("-"):
if argument not in allowed_args:
return # wrong argument given
currentArgument = argument
else:
if argumentDict[currentArgument] != "": # add space when already something given
argumentDict[currentArgument] += " "
argumentDict[currentArgument] += argument
You can then access your parameters via
argumentDict["-u"]
argumentDict["-n"]
argumentDict["-msg"]
The output of
print(argumentDict)
Would be
{'-u': 'def750', '-n': '1', '-msg': 'Hello world!'}
I am not sure if it is something you are looking for, but you could try:
inp = ('-u', 'def750', '-n', '1', '-msg', 'Hello', 'world!')
allowed_args = ["-u", "-n", "-msg"]
dic = {}
current_key = None
for el in inp:
if el in allowed_args:
current_key = el
dic[current_key] = []
else:
dic[current_key].append(el)
for key, val in dic.items():
dic[key] = " ".join(val)
print(dic)
output:
{'-msg': 'Hello world!', '-n': '1', '-u': 'def750'}
There are many approaches to this. One way would be to loop over the arguments and append the arguments based on the state of a flag, although this would be quite verbose.
Another way would be to use itertools.groupby to group subsequent elements based on whether they start with '-', and filter out the dash-prefixed entries using itertools.filterfalse:
import itertools as it
DASH = '-'
args = ('-u', 'def750', '-n', '1', '-msg', 'Hello', 'world!')
parsedargs = it.filterfalse(lambda x: x[0],
it.groupby(args,
lambda y: y.startswith(DASH)))
Or; putting it in a dictionary right away and also filtering out disallowed arguments:
import itertools as it
DASH = '-'
allowed_args = ('-u','-n','-msg')
args = ('-u', 'def750', '-n', '1', '-msg', 'Hello', 'world!',
'-not-allowed', 'asdf', 'qwerty')
argdict = {
k: list(v[1])
for k, v in zip(
[entry for entry in args if entry.startswith(DASH)],
it.filterfalse(lambda x: x[0],
it.groupby(args,
lambda y: y.startswith(DASH)))
)
if k in allowed_args
}
print(argdict)
Resulting in:
{'-u': ['def750'], '-n': ['1'], '-msg': ['Hello', 'world!']}
But is not very readable..
Or perhaps more simple, extensible, and readable; use argparse from the standard library, as it was built for this purpose and offers more funtionality. There are also third party libraries out there which allow easily building a CLI for you program.
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:
So I have the following code:
import random
pizza_toppings = ["bacon", "cheese", "chicken", "pepperoni", "olives"]
pizza_sauce = ["alfredo", "marinara", "ranch", "BBQ"]
def pizza(number_of_toppings):
final_sauce = random.choice(pizza_sauce)
final_toppings = []
for i in range(number_of_toppings):
final_topping = random.choice(pizza_toppings)
final_topping(final_toppings)
final_result = print("Your pizza with ", final_topping, " with ", final_sauce, " is ready I guess...")
return final_result
pizza(2)
It's giving me the error "TypeError: 'str' object not callable." How do I fix this?
I assume this line
final_topping(final_toppings)
should be
final_toppings.append(final_topping)
Also the return of print is None, so final_result will be None.
I replaced final_toppings by final_toppings_list so it makes it clearer :
import random
pizza_toppings = ["bacon", "cheese", "chicken", "pepperoni", "olives"]
pizza_sauce = ["alfredo", "marinara", "ranch", "BBQ"]
def pizza(number_of_toppings):
final_sauce = random.choice(pizza_sauce)
final_toppings_list = []
for i in range(number_of_toppings):
final_topping = random.choice(pizza_toppings)
final_toppings_list.append(final_topping)
final_result = "Your pizza with ", final_toppings_list, " with ", final_sauce, " is ready I guess..."
return final_result
print(pizza(2))
It´s because you´re using the string final_topping as a function. Just delete that line and you´re good.
You don't necessarily need to append final_topping to a final_toppings list if you want to use only one element of your pizza_toppings list (later in final_result).
I commented the two lines in your script and used python f-strings to format final_result in a convenient way..
import random
pizza_toppings = ["bacon", "cheese", "chicken", "pepperoni", "olives"]
pizza_sauce = ["alfredo", "marinara", "ranch", "BBQ"]
def pizza(number_of_toppings):
final_sauce = random.choice(pizza_sauce)
#final_toppings = []
for i in range(number_of_toppings):
final_topping = random.choice(pizza_toppings)
#final_toppings.append(final_topping)
final_result = (
f"Your pizza with {final_topping} "
f"and {final_sauce} is ready I guess..."
)
return final_result
print(pizza(2))
I'm facing quite a tricky problem in my python code. I looked around and was not able to find anyone with a similar problem.
I'd like to generate strings translating some characters into several, different ones.
I'd like that original characters, meant to be replaced (translated), to be replaced by several different ones.
What I'm looking to do is something like this :
text = "hi there"
translations = {"i":["b", "c"], "r":["e","f"]}
result = magicfunctionHere(text,translations)
print(result)
> [
"hb there",
"hc there",
"hi theee",
"hi thefe",
"hb theee",
"hb thefe",
"hc theee",
"hc thefe"
]
The result contains any combination of the original text with 'i' and 'r' replaced respectively by 'b' and 'c', and 'e' and 'f'.
I don't see how to do that, using itertools and functions like permutations, product etc...
I hope I'm clear enough, it is quite a specific problem !
Thank you for your help !
def magicfunction(ret, text, alphabet_location, translations):
if len(alphabet_location) == 0:
ret.append(text)
return ret
index = alphabet_location.pop()
for w in translations[text[index]]:
ret = magicfunction(ret, text[:index] + w + text[index + 1:], alphabet_location, translations)
alphabet_location.append(index)
return ret
def magicfunctionHere(text, translations):
alphabet_location = []
for key in translations.keys():
alphabet_location.append(text.find(key))
translations[key].append(key)
ret = []
ret = magicfunction(ret, text, alphabet_location, translations)
ret.pop()
return ret
text = "hi there"
translations = {"i":["b", "c"], "r":["e","f"]}
result = magicfunctionHere(text,translations)
print(result)
One crude way to go would be to use a Nested Loop Constructin 2 steps (Functions) as depicted in the Snippet below:
def rearrange_characters(str_text, dict_translations):
tmp_result = []
for key, value in dict_translations.items():
if key in str_text:
for replacer in value:
str_temp = str_text.replace(key, replacer, 1)
if str_temp not in tmp_result:
tmp_result.append(str_temp)
return tmp_result
def get_rearranged_characters(str_text, dict_translations):
lst_result = rearrange_characters(str_text, dict_translations)
str_joined = ','.join(lst_result)
for str_part in lst_result:
str_joined = "{},{}".format(str_joined, ','.join(rearrange_characters(str_part, dict_translations)))
return set(str_joined.split(sep=","))
text = "hi there"
translations = {"i": ["b", "c"], "r":["e","f"]}
result = get_rearranged_characters(text, translations)
print(result)
## YIELDS: {
'hb theee',
'hc thefe',
'hc there',
'hi thefe',
'hb thefe',
'hi theee',
'hc theee',
'hb there'
}
See also: https://eval.in/960803
Another equally convoluted approach would be to use a single function with nested loops like so:
def process_char_replacement(str_text, dict_translations):
tmp_result = []
for key, value in dict_translations.items():
if key in str_text:
for replacer in value:
str_temp = str_text.replace(key, replacer, 1)
if str_temp not in tmp_result:
tmp_result.append(str_temp)
str_joined = ','.join(tmp_result)
for str_part in tmp_result:
tmp_result_2 = []
for key, value in dict_translations.items():
if key in str_part:
for replacer in value:
str_temp = str_part.replace(key, replacer, 1)
if str_temp not in tmp_result_2:
tmp_result_2.append(str_temp)
str_joined = "{},{}".format(str_joined, ','.join(tmp_result_2))
return set(str_joined.split(sep=","))
text = "hi there"
translations = {"i": ["b", "c"], "r":["e","f"]}
result = process_char_replacement(text, translations)
print(result)
## YIELDS: {
'hb theee',
'hc thefe',
'hc there',
'hi thefe',
'hb thefe',
'hi theee',
'hc theee',
'hb there'
}
Refer to: https://eval.in/961602
How could I parse the dictionary below, so that it's values only contain ticket numbers?
Current Dictionary:
{'8.8.8.8': 'Open Menu 10A-003272 10A-003328 10A-003652', '8.8.8.9': '10A-003069 10/21/2016', '8.8.8.10': 'Open Menu 10A-003145 10/21/2016'}
Objective Dictionary:
{'8.8.8.8': '10A-003272 10A-003328 10A-003652', '8.8.8.9': '10A-003069', '8.8.8.10': '10A-003145'}
Code used to make dictionary:
with open(esccbList, 'r') as f:
d = {}
for line in f:
d[line.strip()] = next(f, '').strip()
Regex to find ticket numbers:
n = re.search(r'10A-\d{6}',item, re.M|re.I)
Assuming that your ticket number substring will only contain hyphen -, you may use a dict comprhension to achieve this like:
my_dict = {'8.8.8.8': 'Open Menu 10A-003272 10A-003328 10A-003652', '8.8.8.9': '10A-003069 10/21/2016', '8.8.8.10': 'Open Menu 10A-003145 10/21/2016'}
new = {k: ' '.join(i for i in v.split() if '-' in i) for k, v in my_dict.items()}
Final value hold by new dict will be:
{'8.8.8.9': '10A-003069',
'8.8.8.10': '10A-003145',
'8.8.8.8': '10A-003272 10A-003328 10A-003652'}
I have updated my answer to print the dictionary in desired format.
import re
pattern = re.compile(r'10A-\d{6}')
info = {'8.8.8.8': 'Open Menu 10A-003272 10A-003328 10A-003652',
'8.8.8.9': '10A-003069 10/21/2016',
'8.8.8.10': 'Open Menu 10A-003145 10/21/2016'}
output = {}
for key, value in info.items():
tokens = value.split()
val = ''
for token in tokens:
if pattern.match(token):
val = val + token + ' '
val = val.strip()
output[key] = val;
print(output)
It prints:
{'8.8.8.8': '10A-003272 10A-003328 10A-003652',
'8.8.8.9': '10A-003069',
'8.8.8.10': '10A-003145'}
d = { k, clean_ticket(v) for k,v in original_dict.items() if is_ticket(v) }
Looks like is_ticket should be something like
def is_ticket(v):
return "Open Menu" in v
Make a function clean_ticket(v) that strips off the Open Menu
def clean_ticket(v):
return v.split("Open Menu")[1].strip()
Something like that.
I assume you have some function
def is_ticket_number(item):
""" returns True only if item is a ticket number """
return re.search(r'10A-\d{6}',item, re.M|re.I)
Then all you need to do is
d = {k: v for k, v in d.items() if is_ticket_number(v)}