I need help making a GUI with python, Glade,and GTK - python-2.7
i have a program that encodes and decodes messages with a key but i want to make it look nicer and more professional. My code is as follows:
from random import seed, shuffle
#Encoder Function
def Encoder(user_input,SEED):
user_input = user_input.lower()
letter = ["a","b","c","d","e","f","g","h","i","j","k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
Letter_code = {"a":0,"b":1,"c":2,"d":3,"e":4,"f":5,"g":6,"h":7,"i":8,"j":9,"k":10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,'s':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'z':25}
code = ["a","b","c","d","e","f","g","h","i","j","k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',]
n = []
seed(SEED)
shuffle(code)
for letter in user_input:
for let in letter:
if letter != " ":
if letter == let:
first = Letter_code[let]
n.append(code[first])
else:
n.append("~")
return ''.join(n)
#Decoder Function
def Decoder(user_input,SEED):
user_input = user_input.lower
key_list = ["a","b","c","d","e","f","g","h","i","j","k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
final = ["a","b","c","d","e","f","g","h","i","j","k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
seed(SEED)
shuffle(key_list)
key_code = {}
z = 0
n = []
for key in key_list:
key_code[key] = z
z += 1
for let in user_input:
if let != "~":
for Ke in key_list:
if let == Ke:
a = key_code[Ke]
n.append(final[a])
else:
n.append(" ")
return ''.join(n)
i wanted a gui that would have two entry boxes,one for the message and the other for the key, and i wanted it to have two buttons, one would say encode and the other decode. and also a place in the gui where the final message would be printed and be copy-able by the user. would greatly appreciate it if someone could help me with this
Following glade tutorials may help you.
http://www.overclock.net/t/342279/tutorial-using-python-glade-to-create-a-simple-gui-application
https://wiki.gnome.org/Glade/Tutorials
http://www.pygtk.org/articles/pygtk-glade-gui/Creating_a_GUI_using_PyGTK_and_Glade.htm
As for converting the .py to an exe, you can use py2exe, please take a look at this answer - https://stackoverflow.com/a/14165470/2689986
Related
Give random list objects attributes, python 3
I am very new to programming. I have an assignment to design a game similar to minesweeper. So here's what I'm thinking right now on how to make the gameplan with hidden mines. First of all, I create a list which will be printed for the user to see (createPlan is the function which creates the plan, and showPlan is the function who shows the plan). Second, I'm thinking of creating another list which is identical to skapaPlan. However using methods to apply different attributes to the list object. For example,I want to apply a mine to list object nr x. How do I do that and still keep them "connected"? Thanks! class Square: def __init__(mine = False, empty = 0): self.mina = mine .... def createPlan(size, sign): spelplan = [] for i in range(size): gameplan.append([sign]*size) return gameplan def square_attribut(gameplan): gomdplan = spelplan (help) def showPlan(gameplan): i = 0 bracket = list(range(0,len(gameplan))) rownr = [" "] + bracket for row in [bracket]+gameplan: print(rownr[i],end = " ") i += 1 for square in row: print(square,end = " ") print()
Iterating through a .txt file in an odd way
What I am trying to do is write a program that opens a .txt file with movie reviews where the rating is a number from 0-4 followed by a short review of the movie. The program then prompts the user to open a second text file with words that will be matched against the reviews and given a number value based on the review. For example, with these two sample reviews how they would appear in the .txt file: 4 A comedy-drama of nearly epic proportions rooted in a sincere performance by the title character undergoing midlife crisis . 2 Massoud 's story is an epic , but also a tragedy , the record of a tenacious , humane fighter who was also the prisoner -LRB- and ultimately the victim -RRB- of history . So, if I were looking for the word "epic", it would increment the count for that word by 2 (which I already have figured out) since it appears twice, and then append the values 4 and 2 to a list of ratings for that word. How do I append those ints to a list or dictionary related to that word? Keep in mind that I need to create a new list or dicitonary key for every word in a list of words. Please and thank you. And sorry if this was poorly worded, programming isn't my forte. All of my code: def menu_validate(prompt, min_val, max_val): """ produces a prompt, gets input, validates the input and returns a value. """ while True: try: menu = int(input(prompt)) if menu >= min_val and menu <= max_val: return menu break elif menu.lower == "quit" or menu.lower == "q": quit() print("You must enter a number value from {} to {}.".format(min_val, max_val)) except ValueError: print("You must enter a number value from {} to {}.".format(min_val, max_val)) def open_file(prompt): """ opens a file """ while True: try: file_name = str(input(prompt)) if ".txt" in file_name: input_file = open(file_name, 'r') return input_file else: input_file = open(file_name+".txt", 'r') return input_file except FileNotFoundError: print("You must enter a valid file name. Make sure the file you would like to open is in this programs root folder.") def make_list(file): lst = [] for line in file: lst2 = line.split(' ') del lst2[-1] lst.append(lst2) return lst def rating_list(lst): '''iterates through a list of lists and appends the first value in each list to a second list''' rating_list = [] for list in lst: rating_list.append(list[0]) return rating_list def word_cnt(lst, word : str): cnt = 0 for list in lst: for word in list: cnt += 1 return cnt def words_list(file): lst = [] for word in file: lst.append(word) return lst ##def sort(words, occurrences, avg_scores, std_dev): ## '''sorts and prints the output''' ## menu = menu_validate("You must choose one of the valid choices of 1, 2, 3, 4 \n Sort Options\n 1. Sort by Avg Ascending\n 2. Sort by Avg Descending\n 3. Sort by Std Deviation Ascending\n 4. Sort by Std Deviation Descending", 1, 4) ## print ("{}{}{}{}\n{}".format("Word", "Occurence", "Avg. Score", "Std. Dev.", "="*51)) ## if menu == 1: ## for i in range (len(word_list)): ## print ("{}{}{}{}".format(cnt_list.sorted[i],) def make_odict(lst1, lst2): '''makes an ordered dictionary of keys/values from 2 lists of equal length''' dic = OrderedDict() for i in range (len(word_list)): dic[lst2[i]] = lst2[i] return dic cnt_list = [] while True: menu = menu_validate("1. Get sentiment for all words in a file? \nQ. Quit \n", 1, 1) if menu == True: ratings_file = open("sample.txt") ratings_list = make_list(ratings_file) word_file = open_file("Enter the name of the file with words to score \n") word_list = words_list(word_file) for word in word_list: cnt = word_cnt(ratings_list, word) cnt_list.append(word_cnt(ratings_list, word)) Sorry, I know it's messy and very incomplete.
I think you mean: import collections counts = collections.defaultdict(int) word = 'epic' counts[word] += 1 Obviously, you can do more with word than I have, but you aren't showing us any code, so ... EDIT Okay, looking at your code, I'd suggest you make the separation between rating and text explicit. Take this: def make_list(file): lst = [] for line in file: lst2 = line.split(' ') del lst2[-1] lst.append(lst2) return lst And convert it to this: def parse_ratings(file): """ Given a file of lines, each with a numeric rating at the start, parse the lines into score/text tuples, one per line. Return the list of parsed tuples. """ ratings = [] for line in file: text = line.strip().split() if text: score = text[0] ratings.append((score,text[1:])) return ratings Then you can compute both values together: def match_reviews(word, ratings): cnt = 0 scores = [] for score,text in ratings: n = text.count(word) if n: cnt += n scores.append(score) return (cnt, scores)
How to Reduce Code Duplication of If-Else Statements in Python
I'm a student with the very bad habit of duplicating code all over the place, which is something I want to change. Below, I have a snippet of code from a function I'm writing. Quick explanation: The code would look at an HR website for a person, and return info about the employees he's managing (assuming he manages anyone). There are two types of employees: regular employees and contract workers. On the website, regular employees underneath the manager would all be listed under employeeList, and the contractors would be listed under contractWorkerList. response = opener.open('myFakeOrgHierarchy.com/JohnSmith_The_Manager') allDataFromPage = (response.read()) jsonVersionOfAllData = json.loads(allDataFromPage) listOfAllReports = [] numOfEmployeeDirectReports = len(jsonVersionOfAllData['employeeList']['list']) numOfContractWorkerReports = len(jsonVersionOfAllData['contractWorkerList']['list']) if numOfEmployeeDirectReports != 0: for i in range(0, numOfEmployeeDirectReports, 1): workerInfo = {} workerInfo['empLname'] = jsonVersionOfAllData['employeeList']['list'][i]['lastName'] workerInfo['empFname'] = jsonVersionOfAllData['employeeList']['list'][i]['firstName'] listOfAllReports.append(workerInfo) if numOfContractWorkerReports != 0: for i in range(0, numOfContractWorkerReports, 1): workerInfo = {} workerInfo['empLname'] = jsonVersionOfAllData['contractWorkerList']['list'][i]['lastName'] workerInfo['empFname'] = jsonVersionOfAllData['contractWorkerList']['list'][i]['firstName'] listOfAllReports.append(workerInfo) As you can see, I have several lines of code that are almost identical to other lines, with only small variations. Is there a way to check both contractWorkerList and employeeList to see if they're not empty, and (assuming they're not empty) go through both contractWorkerList and employeeList and grab values without duplicating the code? (Since I'm a relative beginner, any simple examples you could provide with your recommendations would be much appreciated)
For starters, every time you see something duplicated, think about creating a variable upfront & use that. After that, you can decide what should be factored out into a function. Below, I just removed most of the duplicated items. response = opener.open('myFakeOrgHierarchy.com/JohnSmith_The_Manager') allDataFromPage = (response.read()) jsonVersionOfAllData = json.loads(allDataFromPage) listOfAllReports = [] for listType in ('employeeList', 'contractWorkerList'): json_ver = jsonVersionOfAllData[listType]['list'] directReports = len(json_ver) if directReports != 0: for i in range(0, directReports, 1): workerInfo = {} for wi_name, json_name in (('empLname', 'lastName'), ('empFname', 'firstName')): workerInfo[wi_name] = json_ver[i][json_name] listOfAllReports.append(workerInfo)
Most common way of avoiding code duplication is to define a function with that code. def checkIfEmpty(numOfReports, listName): if numOfReports != 0: for i in range(0, numOfReports, 1): workerInfo = {} workerInfo['empLname'] = jsonVersionOfAllData[listName]['list'][i]['lastName'] workerInfo['empFname'] = jsonVersionOfAllData[listName]['list'][i]['firstName'] listOfAllReports.append(workerInfo) So You will end up with simple and easy to read code: checkIfEmpty(numOfEmployeeDirectReports, 'employeeList') checkIfEmpty(numOfContractWorkerReports, 'contractWorkerList')
In this particular scenario, you could do something like this: for var, key in [(numOfEmployeeDirectReports, 'employeeList'), (numOfContractWorkerReports, 'contractWorkerList')]: if var != 0: for i in range(0, var, 1): workerInfo = {} workerInfo['empLname'] = jsonVersionOfAllData[key]['list'][i]['lastName'] workerInfo['empFname'] = jsonVersionOfAllData[key]['list'][i]['firstName'] listOfAllReports.append(workerInfo)
Convert from decimal to binary - python
I'm having an issue with this piece of code I wrote. I'm trying to convert an integer input and print an output with its equivalent in binary base. For example for 5 it should drop an output of '101' however it just prints '10' like if it doesn't take into account the last digit. Please any comments would be greatly appreciated T = raw_input() for i in range(0, int(T)): n = raw_input() dec_num = int(n) cnv_bin = '' while dec_num//2 > 0: if dec_num%2 == 0: cnv_bin += '0' else: cnv_bin += '1' dec_num = dec_num//2 print cnv_bin[::-1]
while dec_num//2 > 0: should be: while dec_num > 0: The first time through the loop, 5//2==2, so it continues. The second time through the loop, 2//2==1, so it continues. The third time, 1//2==0 and the loop quits without handling the last bit. Also, you can just do the following to display a number in binary: print format(dec_num,'b') Format string version: print '{0} decimal is {0:b} binary.'.format(5)
Why not use the build-in function bin()? eg: bin(5) output 0b101 If you don't want the prefix(0b), you can exclude it. bin(5)[2:] hope to be helpful!
import math def roundup(n): return math.ceil(n) D = eval(input("Enter The Decimal Value: ")) n = roundup(math.log2(D+1))-1 bi = 0 di = D qi = 0 i = n print("Binary Value:",end = " ") while(i>=0): qi = math.trunc(di/2**i) bi = qi print(bi,end = "") di = di - bi*(2**i) i = i-1
runtime error(nzec) in python
It works fin in my pc and in an online compiler+debugger. However, when I submit it in codechef, it gives me a runtime error(nzec). When do you get a runtime error and how to you resolve it. What is the problem in this code? I keep getting runtime error very frequently. How do I avoid it? Any kind of help will be deeply appreciated! t = int(raw_input()) for i in range(t): a = map(int, raw_input()) if a.index(min(a)) != 0: if min(a) == 0: print a.index(min(a)) else: print str(str(a.index(min(a))) * (min(a)+1)) elif a.index(min(a)) == 0: k = min(a) a[0] = 99 l = min(a) if l == k: print str(str(a.index(min(a))) * min(a)) elif l > k: print '1'+ ('0' * (k+1))
You have to split the raw_input() raw_input() receives the input as just a string. Use raw_input().split() to convert the string to a list. Else you will have indexing problems, since the spaces given in the input are taken for mapping. So you get the nzec (non-zero exit code) error a=map(int,raw_input().split()) will do
Many times it is due to some white places left. Try this: raw_input().strip().split(" ") if the data is separated by " ".