Compressing a sentence into ascii and then decompressing it back - python-3.x

When I'm trying to compress this sentence into the ASCII equivalent, I keep getting this error code TypeError: ord() expected a character, but string of length 5 found
How can I fix the following code
def menu():
print("Compress a file Press 1")
print("Decompress a file Press 2")
print("Quit Press 3")
user_choice = input("")
if user_choice=="1":
compressing()
elif user_choice=="2":
decompressing()
elif user_choice=="3":
import sys
sys.exit()
else:
print("Input invalid.Please enter a number for path selection") , "\n" , menu()
def compressing():
compressed_sentence=[]
sentence=input("Enter a sentence: ")
sentence=sentence.split()
for i in range(len(sentence)):
character=(sentence[i])
ascii_character=ord(character)
compressed_sentence.append(ascii_character)
with open('compressed_file.txt','w') as myFile:
myFile.write(str(compressed_sentence))
menu()
def decompressing():
with open('compressed_file.txt','r') as myFile:
sentence=myFile.read()
for i in sentence:
if i in "[],'":
sentence=sentence.replace(i," ")
new_sentence=sentence.split()
decompressed_sentence=str("")
for i in range(len(new_sentence)):
character=int(new_sentence[i])
decompressed_sentence=(decompressed_sentence+(chr(character)))
final_decompressed_sentence=decompressed_sentence.split()
print(final_decompressed_sentence)
with open('decompressed_file.txt','w') as myFile:
myFile.write(final_decompressed_sentence)
menu()
menu()
in order for it to be able to compress and decompress it properly.

Its okay i got it working:
def menu():
print("Create a file Press 1")
print("Compress a file Press 2")
print("Decompress a file Press 3")
print("Quit Press 4")
user_choice = input("")
if user_choice=="1":
create_a_file()
elif user_choice=="2":
compressing()
elif user_choice=="3":
decompressing()
elif user_choice=="4":
import sys
sys.exit()
else:
print("Input invalid.Please enter a number for path selection") , "\n" , menu()
def create_a_file():
sentence=input("Enter a sentence: ")
sentence=sentence.split()
with open('file.txt','w') as myFile:
myFile.write(str(sentence))
menu()
def compressing():
compressed_sentence=[]
with open('file.txt','r') as myFile:
sentence=myFile.read()
for i in sentence:
if i in "[],'":
sentence=sentence.replace(i," ")
for i in range(len(sentence)):
character=(sentence[i])
ascii_character=ord(character)
compressed_sentence.append(ascii_character)
with open('compressed_file.txt','w') as myFile:
myFile.write(str(compressed_sentence))
menu()
def decompressing():
with open('compressed_file.txt','r') as myFile:
sentence=myFile.read()
for i in sentence:
if i in "[],'":
sentence=sentence.replace(i," ")
new_sentence=sentence.split()
decompressed_sentence=str("")
for i in range(len(new_sentence)):
character=int(new_sentence[i])
decompressed_sentence=(decompressed_sentence+(chr(character)))
final_decompressed_sentence=decompressed_sentence.split()
print(final_decompressed_sentence)
menu()
menu()

Related

i want to print dictionary keys and values separately with given string in python for my project

I'm not able to finish the project given below if someone help me with the particular function paasenger_login ...help me out
The project is flight reservation system with basic pyhton programming
a. Passenger
1. sign in
2.check availability and fare
3.book ticket
b. Cashier
1.approve
2.issue ticket
the code is below
s=[]
class passenger:
pass
class book:
d={}
f={}
pact=1-000-000
new=0
class cashier:
def caslogin():
while True:
print("\t1.Filling Tickets\n\t2.passenger Info\n\t3.Approve Tickets\n\t4.Logout")
x=input()
if x=='1':
if (book.new==0):
flight=int(input("Enter the no of flights: "))
for i in range(flight):
print("Enter name of the flights: ")
q=input()
print("Enter the price for to travel:\n")
op=[]
op.append(input())
book.d[q]=op
print("Successfully loaded:\n")
book.new=1
else:
print("\n\tAlready loaded")
elif x=='2':
if book.pact<=1-000-000:
print("NO user found!................")
else:
for i in range(len(s)):
print(s[i].name,i+1-000-000,s[i].history,s[i].report)
elif x=='3':
if book.pact<=1-000-000:
print("NO record found!................")
else:
for i in s:
print(i.name,i.report)
else:
break
def passenger_login(rn):
while True:
print("Successfully logged in... \n\t1.Book Tickets\n\t2.Approval\n\t3.Logout")
n=input()
if n=='1':
if len(book.d):
for i in book.d:
print(str(i),str(book.d[i]))
else:
break
def __main__():
print("Air Asia\n")
while True:
print("Login as\n\t1.Cashier\n\t2.passenger\n\t3.Exit")
n=input()
if n=='1':
cashier.caslogin()
elif n=='2':
while True:
print("Passenger Info\n\t1.Sign in\n\t2.Sign up\n\t3.Logout")
x=input()
if x=='1':
try:
reg=int(input("Enter the serial no:\n"))
Pass=input("Enter the password:\n")
except:
print("Enter the serial no:")
try:
reg=int(input("Enter the serial no:\n"))
Pass=input("Enter the password:\n")
except:
print("Try after few minutes")
if reg != len(s):
print("NO account found")
else:
if s[reg-1-000-000].ps==Pass:
passenger_login(reg-1-000-000)
elif x=='2':
s.append(passenger())
s[book.pact - 1-000-000].name=input("Enter your name:\n")
s[book.pact - 1-000-000].ps=input("create password:\n")
s[book.pact - 1-000-000].history=0
s[book.pact - 1-000-000].report="New user"
print("Your serial no is : ",book.pact)
book.pact+=1
else:
break
else:
break
__main__()

Python3 - hangmanClearScreen

After I finish my hangman game, when I clear the console, it clears everything. However, I want it to not clear the menu. How do I fix this?
Here is my code:
import random, os
import time
print("^^^^^^^^^^THIS IS HANGMAN^^^^^^^^^^")
print("1. Play Game ")
print("2. Quit Game ")
choice = input("Please enter option 1 or 2")
if choice == "1":
words = ["handkerchief", "accommodate", "indict", "impetuous"]
word = random.choice(words)
guess = ['_'] * len(word)
guesses = 7
while '_' in guess and guesses > 0:
print(' '.join(guess))
character = input('Enter character: ')
if len(character) > 1:
print('Only enter one character.')
continue
if character not in word:
guesses -= 1
for i, c in enumerate(word):
if c == character:
guess[i] = character
if guesses == 0:
print('You LOST!')
break
else:
print('You have only', guesses, 'chances left to win.')
else:
print(''.join(guess))
print('You WON, well done')
time.sleep(2)
import os
os.system('clear')
I don't know how to make the code so that it only clears down to the menu
simply wrap your menu in a function
def menu():
print("^^^^^^^^^^THIS IS HANGMAN^^^^^^^^^^")
print("1. Play Game ")
print("2. Quit Game ")
and reprint it after you clear the console
import os
os.system('clear')
menu()
if you want your menu to still work after the clear, just include all the code you use to make your menu work into the menu() function. Good luck on your project

Issue With Function Continuation in Python

I know this is probably a very simple fix, but I cannot seem to make the code work. Here is the problematic excerpt:
def main_menu():
print("Welcome! Please Choose An Option to Proceed")
print("1. New: Input Letters Into A New Excel Document")
print("2. Add: Add New Letters To An Existing Excel Document")
while True:
choice = input("Enter Option Number: ")
if choice.lower() in ['1','2']:
return choice.lower()
else:
print("Invalid Number Choice")
continue
def menu_choice(main_menu):
while True:
choice = main_menu()
if choice == "1":
newsession()
elif choice == "2":
addsession()
else:
break
def newsession():
while True:
try:
txtfilenameinput = input("1. Enter 'Txt' Input File Name: ")
inputfilename = txtfilenameinput.replace(".txt" , "")
inputfile = codecs.open(inputfilename + ".txt" , "r" , encoding = "utf-8" , errors = "ignore")
print("File Found" + "\n")
break
except FileNotFoundError:
print("File Not Found: Make Sure The File Is Spelled Correctly And That Both The Program and File Is On The Desktop Screen" + "\n")
if __name__ == '__main__':
main_menu()
closeprogram = input("Press Enter Key To Close Program")
My objective is, for example, when an input of "1" is inserted in main_menu(), the script would then start to run the newsession() function. Yet for some reason, the program does nothing but jumps to the end of the script (a "press key to close program" command) without engaging the newsession() function. This holds true for an input of "2" for the addsession() function as well. What am I doing wrong? I have tried everything but nothing allows my input choice of 1 or 2 to continue the progress in my script. Thank you for your help!
Try the code below. It allows to exit from the program and it returns again and again for more user input:
def main_menu():
print("Welcome! Please Choose An Option to Proceed")
print("1. New: Input Letters Into A New Excel Document")
print("2. Add: Add New Letters To An Existing Excel Document")
print(" QUIT with 'q'")
while True:
choice = input("Enter Option Number: ")
if choice.lower() in ['1','2','q']:
return choice.lower()
else:
print("Invalid Number Choice")
continue
def menu_choice(main_menu):
while True:
choice = main_menu()
if choice == "1":
newsession()
elif choice == "2":
addsession()
else:
break
The problem with your code was that you were "trapped" in a while True: loop with no escape. So after ONE single user choice newsession() or addsession() were started again and again with no further progress in the script and no way to change anything about it except to kill the program. Remember: each while True loop should have at least one line containing brake or return, else it is a never ending story ...
The problem with not reaching the newsession() is HERE:
if __name__ == '__main__':
main_menu()
where it should be:
if __name__ == '__main__':
menu_choice()

Xor Memory Error

This is my simple python xor encryption program, it works on every file i tried except when i used on an audio file which gave me a memory error, how do i fix it so it works on bigger files? The audio file i used it on was a wav audio file.
def encrypt(file,key):
count=0
encrypt=[]
openfile=open(file,"rb")
msg=openfile.read()
openfile.close()
for i in msg:
if count>=len(key):
count=0
encrypt.append(i^ord(key[count]))
count+=1
encryptmsg=''.join(chr(e) for e in encrypt)
ext=input('Saving...File Name (with extension)? ')
file= open(ext, "wb")
file.write(str.encode(encryptmsg))
file.close()
print(encryptmsg)
input("Press Enter to Continue...")
def decrypt(file,key):
count=0
decrypt=[]
openfile=open(file,"rb")
msg=openfile.read()
openfile.close()
for i in msg:
if count>=len(key):
count=0
decrypt.append(i^ord(key[count]))
count+=1
decryptmsg=''.join(chr(e) for e in decrypt)
ext=input('Saving...File Name (with extension)? ')
file= open(ext, "wb")
file.write(str.encode(decryptmsg))
file.close()
print(decryptmsg)
input("Press Enter to Continue...")
ans = input("0.Encrypt 1.Decrypt?")
file = input("File? ")
key = input("Key? ")
if ans=='0':
encrypt(file,key)
elif ans=='1':
decrypt(file,key)
else:
quit()

Error writing text into a .txt file in python

I am making a program that will
1. Create a text file
2. Allow a password to be stored
3. Allow a password to be changed
4. Add an additional password
5. Delete a specific password
The problem is in def delete():. I put in three passwords on three seperate lines: first, second, third. When I choose to delete password "second", it reprints the list from before, and then prints the new list at the end of the last password.
Here is my code:
import time
def create():
file = open("password.txt", "w")
passwordOfChoice = input("The password you want to store is: ")
file.write(passwordOfChoice)
print ("Your password is: ", passwordOfChoice)
file.close()
time.sleep(2)
def view():
file = open("password.txt","r")
print ("Your password is: ",
"\n", file.read())
file.close()
time.sleep(2)
def change():
file = open("password.txt", "w")
newPassword = input("Please enter the updated password: ")
file.write(newPassword)
print ("Your new password is: ", newPassword)
file.close()
time.sleep(2)
def add():
file = open("password.txt", "a")
extraPassword = input("The password you want to add to storage is: ")
file.write("\n")
file.write(extraPassword)
print ("The password you just stored is: ", extraPassword)
file.close()
time.sleep(2)
def delete():
phrase = input("Enter a password you wish to remove: ")
f = open("password.txt", "r+")
lines = f.readlines()
for line in lines:
if line != phrase+"\n":
f.write(line)
f.close()
print("Are you trying to: ",
"\n1. Create a password?",
"\n2. View a password?",
"\n3. Change a previous password?",
"\n4. Add a password?",
"\n5. Delete a password?",
"\n6. Exit?\n")
function = input()
print("")
if (function == '1'):
create()
elif (function == '2'):
view()
elif (function == '3'):
change()
elif (function == '4'):
add()
elif (function == '5'):
delete()
elif (function == '6'):
print("Understood.", "\nProgram shutting down.")
time.sleep(1)
else:
print("Your answer was not valid.")
print("Program shutting down...")
time.sleep(1)
To show what I meant above, here is my output:
Your password is:
first
second
thirdfirst
third
Can someone please tell me how to fix my def delete(): function so that it will not rewrite the original data? Thanks a ton!
The problem lies with the 'r+' mode. When you use 'r+' you can read and write, sure, but it's up to you to control where in the file you write.
What's happening is you read the file, and the cursor is stuck at the end, so when you write it back, Python dutifully puts your new lines on the end of the file.
See the docs about file methods; you're looking for something like seek.

Resources