I have a python code that a friend made , as I have very small knowledge of python..
I want to convert it into a GUI as we will distribute the code as a program for it to be beginner-friendly .
anyways here's the code:
import time, os, sys
try:
if len(sys.argv) < 2:
fn = raw_input("Enter the name of the file you want to edit: ")
else: fn = sys.argv[1]
f = open(fn)
b = f.read()
for i in b[:300]:
print hex(ord(i))[2:],
f.close()
line = str(0x15c)+'-'+str(0x15f)
if len(sys.argv)<3:
hexcode = raw_input("3 bytes color hex number: ")
else: hexcode = sys.argv[2]
if not hexcode.startswith('0x'):
hexcode = '0x'+hexcode
hexstr = '0x'
start = int(line.split('-')[0])
end = int(line.split('-')[1])
for i in b[start:end]:
hexstr+=hex(ord(i))[2:]
ascii = ''
for i in range(2,len(hexcode),2):
char = chr(int(hexcode[i:i+2],16))
ascii+=char
b = b[:start]+ascii+b[end:]
for i in b[:300]:
print hex(ord(i))[2:],
except Exception, x:
print x
time.sleep(3)
finally:
f = open(fn,'wb')
f.write(b)
f.close()
Now I found this on a tutorial but don't know how to use it:
#simple GU0I
from Tkinter import *
root = Tk()
root.title("BreffHexReplace")
root.geometry("400x200")
app = Frame(root)
app.grid()
label = Label(app, text = "This is a label!")
label.grid()
root.mainloop()
Any help?
thanks!
also one more thing , in this code , after I type in the name or the replacor hex , it shows me a list of hex , how can I make it not shown?
thanks!
Because this program is so simple, you can try EasyGui( easygui.sourceforge.net/ ). To start, add import easygui as eg. This line loads the EasyGui module. Next, replace fn = raw_input("Enter the name of the file you want to edit: ") with fn = eg.fileopenbox(title = 'HexReplace', msg = 'Browse to the file you wish to edit'). This opens a box to browse to the wanted file. Also replace hexcode = raw_input("3 bytes color hex number: ") with hexcode = eg.enterbox(msg = '3 bytes color hex number', title = 'HexReplace'). This pops up an input box. Replace print x with eg.msgbox(title = 'HexReplace', msg = x). This shows a message box with the exception. The title argument is the window title. To remove the hex list, add between the imports and the try block: null = open(os.devnull, 'W's); oldstdout = system.stdout; sys.stdout = null
This will silence all print messages.
Related
Code:
import secrets
import sys
import time
import string
from tenacity import (retry , stop_after_attempt)
#Required Defs
var = open('conf.txt','r+')
content = var.read()
print(content)
def get_random_string(length):
letters = string.ascii_lowercase
num = string.ascii_uppercase
punc = string.punctuation
spec = string.hexdigits
one = str(num) + str(punc) + str(spec)
result_str = ''.join(secrets.choice(one) for i in range(length))
print("Random string of length", length, "is:", result_str)
#Closing All Defs Here
#retry(stop=stop_after_attempt(5))
def start():
pasw = input("Do YOu Want A Random Password: y/n: ")
if pasw == 'y':
leng = input("Please Type The Length Of The Password You Want: ")
try:
len1 = int(leng)
get_random_string(len1)
time.sleep(4)
except ValueError:
print("Only Numbers Accepted")
time.sleep(4)
elif pasw == 'n':
sys.exit("You Don't Want TO Run The Program")
time.sleep(3)
else:
raise Exception("Choose Only From 'y' or 'n'")
start()
Problem:
I want to read contents of file called conf.txt and want to include
only 2 chars 3 letters and it is based on conf.txt. How can I achieve
this? Please tell conf.txt contains:
minspec = 1 #This tells take 2 special chars chars
minnumbers = 3 #This tells take 3 Numbers
minletter = 2 #This tells take 2 lower chars
minhex = 2 #This tells take 2 hex numbers
with open('file.txt', 'r') as data:
contents = data.read()
In the above example we are opening file.txt in read mode with the object name data.
We can use data.read() to read the file and store it in the variable name contents.
One of the advantage of using with is that we don't need to close the file, it automatically closes file for you.
For reading only selected bytes for a file object can be used:
the seek method (to change the file object’s position);
the read method has the optional param - number of bytes to read.
Example:
f = open('workfile', 'rb') # b'0123456789'
f.read(2) # reading only the first two bytes(b'01')
f.seek(6) # go to the 6th byte in the file
f.read(3) # reading 3 bytes after 6 position(b'678')
I'm writing a text encoder/crypter (all by myself) and i can't understand how to append and replace characters in the string :-/
The code:
import os, sys, random
dig = 0
text_encoded = ""
text = ""
try:
if os.path.isfile(sys.argv[1]) == True:
with open(sys.argv[1], "r") as text:
text = text.readlines()
except:
pass
if text == "":
print("Write the text to encode")
text = input()
text = text.split()
for _ in range(len(text)):
text_encoded = text[dig].replace("qwertyuiopasdfghjklzxcvbnm ", "mnbvcxzlkjhgfdsapoiuytrewq#")
dig = dig+1
print("Your encoded text is:\n"+text_encoded)
Here is some output:
Write the text to encode
lo lolo lol lol
Your encoded text is:
lol
If you can help me in any way, thank you :-)
If I'm getting you correctly, you want to replace q with m, w with n and so on. Try the following
import os, sys, random
dig = 0
text_encoded = ""
text = ""
try:
if os.path.isfile(sys.argv[1]) == True:
with open(sys.argv[1], "r") as text:
text = text.readlines()
except:
pass
if text == "":
print("Write the text to encode")
text = input()
mychars=list("qwertyuiopasdfghjklzxcvbnm ")
myencode=list("mnbvcxzlkjhgfdsapoiuytrewq#")
charmap=zip(mychars,myencode)
_map = dict(charmap)
encoded_text = ''.join(_map.get(c) for c in text)
print("Your encoded text is:\n"+encoded_text)
The strings in your question mention that you want to replace ' ' with #. If you do not want to do that, just remove the last characters from both of the above strings.
have two lists instead of strings like from_ = "abc".split() and to_ = "def".split()
look for your char in from_ and get the index, get the same index char from to_ and stitch it to a new sentence.
example:
from_ = "abc".split()
to_ = "def".split()
old_msg = "ab ab"
new_msg = ""
for each in old_msg.split():
new_msg = new_msg + to_[from_.index(each)]
Hope this helps, please add missing char handling and any other edge cases
Or you can use str.translate
import os, sys, random
from pathlib import Path
TEXT_MAP = ("qwertyuiopasdfghjklzxcvbnm ", "mnbvcxzlkjhgfdsapoiuytrewq#")
def main():
text = ''
if len(sys.argv) > 1:
fname = sys.argv[1]
p = Path(fname)
if p.is_file():
text = p.read_text().strip()
print(f'Text from {p} is: {text}')
if not text:
text = input("Write the text to encode: ").strip()
trantab = str.maketrans(*TEXT_MAP)
text_encoded = text.translate(trantab)
print("Your encoded text is:\n"+text_encoded)
if __name__ == '__main__':
main()
import os
import random
import sys
def search(a):
datafile = open("test.txt","r")
quote = datafile.read()
quote_list = quote.split(" ")
d = len(quote_list)
print(quote_list)
for x in range(0,4):
string = quote_list.pop()
print(string)
if(string==a):
return 0
else:
continue
print("Enter the word to search")
b = sys.stdin.readline()
c=search(b)
if(c==0):
print("Found")
else:
print("Not Found")
This code for searching a particular string in a text file is not working. Please help me to rectify the issue.
Try changing the line:
c=search(b)
to:
c=search(b.strip())
The newline in the user-input is probably what's getting in your way.
Other than that you probably want to change:
for x in range(0,4):
to:
for x in quote_list:
and get rid of the parameter d
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hey guys so I have a lengthy code here I need help with,
specifically: my end process is an assignment creating a word cloud, But I haven't even start at that point yet. As of now, I've been able to create the function of creating a frequency accumulator and my first GUI platform.
When running the program, the gui asks the user to type in the file name of their program. However, you can type gibberish or even leave it blank, click the transform file button, and it still opens up Shell and prompts the user for the text file name and then the number of words they want in the list.
I don't even want the 2nd part (asking how many words) but I didn't know another way of doing it for my frequency counter.
from graphics import *
##Deals with Frequency Accumulator##
def byFreq(pair):
return pair[1]
##Function to allow user to upload their own text document##
def FileOpen(userPhrase):
filename = input("Enter File Name (followed by .txt): ")
text = open(filename, 'r').read()
text = text.lower()
for ch in ('!"#$%&()*+,-./:;<=>?#[\\]^_{}~'):
text = text.replace(ch, " ")
words = text.split()
counts = {}
for w in words:
counts[w] = counts.get(w,0) + 1
n = eval(input("Output how many words?"))
items = list(counts.items())
items.sort(key=byFreq, reverse=True)
for i in range(n):
word, count = items[i]
print("{0:<15}{1:>5}".format(word, count))
##This Function allows user to simply press button to see an example##
def Example():
win = GraphWin("Word Cloud", 600, 600)
file = open("econometrics.txt", "r", encoding = "utf-8")
text = file.read()
text = text.lower()
for ch in ('!"#$%&()*+,-./:;<=>?#[\\]^_{}~'):
text = text.replace(ch, " ")
words = text.split()
counts = {}
for w in words:
counts[w] = counts.get(w,0) + 1
n = eval(input("Output how many words?"))
items = list(counts.items())
items.sort(key=byFreq, reverse=True)
for i in range(n):
word, count = items[i]
print("{0:<15}{1:>5}".format(word, count))
#########################################################################
##Gold Boxes##
def boxes(gwin, pt1, pt2, words):
button = Rectangle(pt1, pt2)
button.setFill("gold")
button.draw(gwin)
#Middle of the box coordinates
labelx = (pt1.getX() + pt2.getX())/2.0
labely = (pt1.getY() + pt2.getY())/2.0
#Labels
label = Text(Point(labelx,labely),words)
label.setFill("black")
label.draw(gwin)
####GUI function#####
def main():
#Creates the actual GUI
win = GraphWin("Word Cloud Prompt", 600, 600)
#Box which user types into:
inputBox = Entry(Point(300,150),50)
inputBox.draw(win)
#Gold Boxes at Top
boxes(win, Point(220,300), Point(370,350), "Transform Text File")
boxes(win, Point(220,400), Point(370,450), "Example text file")
#Tells user what to do
prompt = Text(Point(300,25),"Welcome to the Word Cloud program!")
prompt.draw(win)
prompt = Text(Point(300,125),"Enter your textfile name")
prompt.draw(win)
prompt = Text(Point(300,180),"Want to see our own file into a Word Cloud? Click below")
prompt.draw(win)
#display answer
display = Text(Point(300, 500),"")
display.draw(win)
#User Clicks a box:
pt = win.getMouse()
#Store user info
userPhrase = inputBox.getText()
key = inputBox.getText()
#Incase a button isn't clicked
output = "No button was clicked, Please restart program"
#Clicking the Transform Text File Button
if pt.getY() >= 300 and pt.getY() <= 350:
if pt.getX() >= 220 and pt.getX() <= 370:
output = FileOpen(userPhrase)
#Clicking the Example Text File Button
if pt.getY() >= 400 and pt.getY() <= 450:
if pt.getX() >= 220 and pt.getX() <= 370:
output = Example()
#State Answer
display.setText(output)
display.setFill("purple3")
display.setStyle("bold")
prompt.setText("Thank You! Click anywhere to close!")
prompt.setFill("red")
#closing program
pt = win.getMouse()
win.close()
main()
(Editor's Note: I've modified some of the formatting for my ease of reading, but the function will be identical)
def FileOpen(userPhrase):
"""FileOpen allows users to upload their own text document."""
filename = input("Enter File Name (followed by .txt): ")
text = open(filename, 'r').read()
text = text.lower()
for ch in ('!"#$%&()*+,-./:;<=>?#[\\]^_{}~'):
text = text.replace(ch, " ")
words = text.split()
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
n = eval(input("Output how many words?"))
items = list(counts.items())
items.sort(key=byFreq, reverse=True)
for i in range(n):
word, count = items[i]
print("{0:<15}{1:>5}".format(word, count))
This is the function we're concerned with. You call it with an argument userPhrase that comes from a gui text entry field, but then you never use userPhrase anywhere in the function. Consider instead:
def file_open(userPhrase=None):
# file_open is lowercase and snake_case for PEP8
# userPhrase=None to make it an optional argument
filename = userPhrase if userPhrase is not None else \
input("Enter file name (including extension): ")
...
Then you'll have to call it differently if you want file_open to prompt for a filename if not given one.
def main():
...
if 300 <= pt.getY() <= 350 and 220 <= pt.getX() <= 370:
# you can chain conditionals as above. It makes it much easier to read!
# `a <= N <= b` is easily read as `N is between a and b`
userPhrase = inputBox.getText()
if userPhrase.strip(): # if there's something there
file_open(userPhrase)
else:
file_open()
Below is the code I have so far for a simple Caesar cipher program, I am having issues trying to output the encoded data to the graphics window.
The program runs right. But the only output that appears on the screen is the first letter of the coded message, I need the whole coded message to appear on the graphics window.
I think it might be a problem with my loop but can't figure it out. I tried moving the loop around but that just gave two or three repetitions of the first letter.
Any help would be appreciated.
from graphics import*
def main():
win = GraphWin("Caeser Cipher",500,500)
win.setCoords(0.0,0.0,5.0,5.0)
Text(Point(2,4.8),"Caesar Ciper").draw(win)
label1 = Text(Point(1,4),"Please input file:").draw(win)
inputFileName = Entry(Point(2.5,4,),20)
inputFileName.draw(win)
button1 = Text(Point(2.5,3.5),"Open").draw(win)
Rectangle(Point(2.25,3.3),Point(2.75,3.7)).draw(win)
label = Text(Point(1,2.5),"Please input step:")
label.draw(win)
inputstep = Entry(Point(2.5,2.5),20)
inputstep.draw(win)
button2 = Text(Point(2.5,2.0),"Encode").draw(win)
Rectangle(Point(2.25,1.8),Point(2.75,2.2)).draw(win)
button3 = Text(Point(4,1),"Save").draw(win)
Rectangle(Point(3.75,0.8),Point(4.25,1.2)).draw(win)
button4 = Text(Point(4,0.5),"Quit").draw(win)
Rectangle(Point(3.75,0.3),Point(4.25,0.7)).draw(win)
output2 = Text(Point(2.5,1.5),' ')
output2.setTextColor('blue')
output2.draw(win)
while True:
P = win.getMouse()
if(P.getX()>2.25 and P.getX()<2.75 and P.getY()>3.3 and P.getY()<3.7):
fnamein = inputFileName.getText()
infile = open(fnamein, encoding='utf-16', mode='r')
content = infile.read()
output = Text(Point(2.5,3),100)
output.setText(content)
output.setTextColor('red')
output.draw(win)
#infile.close()
if(P.getX()>2.25 and P.getX()<2.7 and P.getY()>1.8 and P.getY()<2.2):
content.strip()
words = content.split()
inputstep1 = inputstep.getText()
#print(inputstep1)
encodedcontent = ' '
for numStr in content:
codeNum = ord(numStr)
#print(codeNum)
encodedcontent = chr(codeNum-eval(inputstep1))
encodedcontent_ascii = ord(numStr)-int(inputstep1)
#print(encodedcontent)
#encodedcontent = encodedcontent + ''
print(encodedcontent)
if(encodedcontent_ascii)<ord('a'):
encodedcontent_ascii = encodedcontent_ascii + 26
#print(encodedcontent_ascii)
'''if str.isalpha(encodedcontent):
encodedcontent = encodedcontent + chr(encodedcontent_ascii)
else:
label.setTextColor('red')'''
encodedcontent = encodedcontent + chr(encodedcontent_ascii)
output2.setText(encodedcontent)
if(P.getX()>3.75 and P.getX()<4.25 and P.getY()>0.8 and P.getY()<1.2):
fnameout = 'encrypt.txt'
data = encodedcontent
outfile = open(fnameout,encoding='utf-16',mode='w')
outfile.write(data)
outfile.close()
if(P.getX()>3.75 and P.getX()<4.25 and P.getY()>0.3 and P.getY()<0.7):
win.close()
main()
I think the problem lies in this loop:
encodedcontent = ' ' # initialise
for numStr in content:
...
encodedcontent = chr(codeNum-eval(inputstep1)) # overwrite
...
encodedcontent = encodedcontent + chr(encodedcontent_ascii) # add
encodedcontent will only be two characters at most, when presumably you want to build up the whole string.
More generally, putting all of your code into one place makes this difficult to debug. I suggest breaking it into smaller functions; at the very least, separate the encryption of a string out from the user interface.