Python ValueError: chr() arg not in range(0x110000) - python

import enchant
message_decrypt= input("Enter the message you want to decrypt: ")
key= 0
def caesar_hack(message_decrypt,key):
final_message=""
d= enchant.Dict("en.US")
f= d.check(message_decrypt)
while f== False:
for characters in message_decrypt:
if ord(characters)<=90:
if ord(characters)-key<ord("A"):
final_message= final_message+ chr(ord(characters)-key)
else:
final_message= final_message+ chr(ord(characters)-key+26)
else:
if ord(characters)-key<ord("a"):
final_message=final_message+chr(ord(characters)-key)
else:
final_message= final_message+chr(ord(characters)-key+26)
key=key+1
f= d.check(message_decrypt)
else:
print(final_message)
caesar_hack(message_decrypt, key)
Why doesn't this code work?
I'm trying to do a caesar cipher hack using the brute force technique. I get an error as below
Can someone please help fix this code.

There's a couple of tweaks I had to make to get your code to work, here's a working version:
import enchant
message_decrypt= input("Enter the message you want to decrypt: ")
key= 0
def caesar_hack(message_decrypt,key):
final_message=""
d= enchant.Dict("en.US")
f= d.check(message_decrypt)
while f== False:
for characters in message_decrypt:
if ord(characters)<=90:
if ord(characters)-key<ord("A"):
final_message= final_message+ chr(ord(characters)-key+26) # The additional 26 should be here, not below
else:
final_message= final_message+ chr(ord(characters)-key)
else:
if ord(characters)-key<ord("a"):
final_message=final_message+chr(ord(characters)-key+26) # The additional 26 should be here, not below
else:
final_message= final_message+chr(ord(characters)-key)
key=key+1
f= d.check(final_message) # Check should be on final_message, not message_decrypt
if not f:
final_message = "" # Need to reset the final_message if not matched
else:
print(final_message)
caesar_hack(message_decrypt, key)
I've commented the main changes I made. One key one was checking final_message in the loop, not message_decrypt (and resetting it again for the next loop if no match).
The other was that your addition of 26 to the character ordinal if it was out of range needed to be moved. Without doing that, it was generating non-printable characters so the check was failing with an enchant error.

Related

How to make a quiz with answers from an external file?

I am trying to make a quiz but my answers are in an external file, so but everytime I run it with my correct answers they say they are incorrect.
Here is my code:
randNum = int(random.randint(0, 4))
song = open("songList.csv","rt")
with open("songList.csv", "rt") as f:
songn = str(song.readlines()[randNum])
reader= csv.reader(f)
for row in reader:
print (songn[0])
guess = input("What is the song called?")
score = 0
correct_guess = False
while True:
if guess == songn:
correct_guess = True
break
score += 1
if score>=total:
break
song_guess = input("Incorrect! Try again:\n> ")
if correct_guess:
print("Answer correct!")
else:
print("game over")
As pointed out in the comments, you have trailing newline characters in one of the strings. Hence they aren't equal.
However I wouldn't just remove the newline. It is always good practice, if your logic allows it, to normalize strings before you test for equality. There are lots of things you can do to normalize:
def normalize(string):
string = string.strip() # Remove any leading or trailing whitespaces
string = string.lower() # Make all letters lowercase
string = " ".join(string.split()) # If the user hit spacebar twice, for example, will remove the double space. Note can have side effects.
return string
Then check
if normalize(string1) == normalize(string2):
do_something()
In fact, if you are dealing with user input, even this might not be sufficient. For example, if the user makes a typo, it won't match.
So I recommend also looking at the fuzzywuzzy library
from fuzzywuzzy import fuzz
def similar(string1, string2):
ratio = fuzz.ratio(string1, string2)
return ratio >= 85 # number between 0 and 100. Higher means fewer differences are allowed
Fuzzywuzzy is very powerful and easy to use. For more info: https://github.com/seatgeek/fuzzywuzzy

How do you print a variable as a string for the length of an input?

my task is when I type 'z' i get the outcome of 'w'.
This works.
However, if I input 'zzzz' only a single 'w' is outputted.
My question is how can I print 'w' for the number of times I enter z.
I am relatively new to StackOverflow. I'm sorry if I have broken any rules or my question is not correctly phrased.
z='w'
while True:
plaintext=input('enter a word to get its ciphertext')
i=list(plaintext)
print (i)
if 'z' in plaintext
print("w")
You are overcomplicating it. The variable you get from input() is a string. Simply use str.replace().
while True:
plaintext = input('enter a word to get its ciphertext')
plaintext_rep = plaintext.replace('z','w')
print(plaintext_rep)
Try looping through the text to get all of the letters
z='w'
while True:
plaintext=input('enter a word to get its ciphertext')
i=plaintext
for letter in i :
if(letter == 'z'):
print ('w')

Converting characters in a variable to their original ascii form

Okay, so I've been doing a lot of research and I couldn't find any answers so I came here to ask for some help.
My problem that I have encountered is I am having trouble taking a variable, then in the background of my code converting each individual string of that variable back to its ascii form and manipulating it using math, such as +, -, * and /. Here is my code..
Note: I had one theory, which is using a for loop to say for each character in this variable, do... blah blah. Here's my code anyways.
import random
import sys
import time
invalid_input = True
def start():
print("Welcome to the Encryption / Decryption Program!")
menuAnswer = input("Please select the number corresponding to the option you would like (1 - 3)\n---------------------------------\n[1] Encrypt\n[2] Decrypt\n[3] Exit the program\n---------------------------------\n")
if menuAnswer == '1':
print("You have chosen to Encrypt!")
invalid_input = False
message = open("sample.txt","r")
msgName = input("What is the name of the text document you would like to Encrypt?\n")
msgName = msgName.upper()
if msgName == 'SAMPLE':
key = '' #This variable will have the encryption key stored inside of it.
for i in range(0,8):
random_number = (random.randint(33,162)) #Generate a random ascii number from the range 33 to 162
key +=str(chr(random_number)) #Convert and store this ascii number as a character to the variable 'Key'
print(key)
print("Remember this key, as you will need it to decrypt your file!")
#\\ Offset //# #Finding the offset, must be able to convert each individual character of the key variable and return it to its usual form to manipulate using math.
else:
print("Invalid Filename")
elif menuAnswer == '2':
print("You have chosen to Decrypt!")
invalid_input = False
elif menuAnswer == '3':
print("You have chosen to exit!")
invalid_input = False
time.sleep(1)
print("Exiting...")
time.sleep(1.5)
exit()
else:
print("Invalid Input, Please try again!")
while invalid_input:
start()
Sorry if this question was difficult to understand, I am really confused myself and have been stuck on this for a week straight.
If I understand correctly you want to convert each character of your string to its ascii number and then do some sort of math operation on it and then convert it back to a string which you can do using ord() like so
s = 'Sample'
tmp = ''
for i in s:
tmp += chr(ord(i)+1)
print tmp
Tbnqmf
Although with the code you have you don't need to convert it to a string and then back to characters to manipulate it you can just manipulate it as soon as you pick a random number like so
import random
def start():
key = ''
for i in range(0,8):
random_number = (random.randint(33,162))
key +=chr(random_number+1)
print(key)
start()
Note you need to be careful when manipulating your characters since you could manipulate it to a number that is not an ascii character

Restricting the User Input to Alphabets

I'm a technical writer learning python. I wanted to write a program for validating the Name field input,as a practise, restricting the the user entries to alphabets.I saw a similar code for validating number (Age)field here, and adopted it for alphabets as below:
import string
import re
r = re.compile(r'[a-zA-Z]+')
print "WELCOME FOR NAME VERIFICATION. TYPE ALPHABETS ONLY!"
print raw_input("Your Name:")
x = r
if x == r:
print x
elif x != r:
print "Come on,'", x,"' can't be your name"
print raw_input("Your Name:")
if 5<=len(x)<=10:
print "Hi,", x, "!"
elif len(x)>10:
print "Mmm,Your name is too long!"
elif len(x)<5:
print "Alas, your name is too short!"
raw_input("Press 'Enter' to exit!")
I intend this code block to do two things. Namely, display the input prompt until the user inputs alphabets only as 'Name'. Then, if that happens, process the length of that input and display messages as coded. But, I get two problems that I could not solve even after a lot of attempts. Either, even the correct entries are rejected by exception code or wrong entries are also accepted and their length is processed.
Please help me to debug my code. And, is it possible to do it without using the reg exp?
If you're using Python, you don't need regular expressions for this--there are included libraries which include functions which might help you. From this page on String methods, you can call isalpha():
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.
I would suggest using isalpha() in your if-statement instead of x==r.
I don't understand what you're trying to do with
x = r
if x == r:
etc
That condition will obviously always be true.
With your current code you were never saving the input, just printing it straight out.
You also had no loop, it would only ask for the name twice, even if it was wrong both times it would continue.
I think what you tried to do is this:
import string
import re
r = re.compile(r'[a-zA-Z]+')
print "WELCOME FOR NAME VERIFICATION. TYPE ALPHABETS ONLY!"
x = raw_input("Your Name:")
while not r.match(x):
print "Come on,'", x,"' can't be your name"
x = raw_input("Your Name:")
if 5<=len(x)<=10:
print "Hi,", x, "!"
elif len(x)>10:
print "Mmm,Your name is too long!"
elif len(x)<5:
print "Alas, your name is too short!"
raw_input("Press 'Enter' to exit!")
Also, I would not use regex for this, try
while not x.isalpha():
One way to do this would be to do the following:
namefield = raw_input("Your Name: ")
if not namefield.isalpha():
print "Please use only alpha charactors"
elif not 4<=len(namefield)<=10:
print "Name must be more than 4 characters and less than 10"
else:
print "hello" + namefield
isalpha will check to see if the whole string is only alpha characters. If it is, it will return True.

How do I make this only print the last value?

I have the fallowing code to encrypt a massage:
massage= raw_input("Enter message to be encrypted: ")
spec = chr(0b1010101)
key = ord(spec)
encrypt = ""
for i in range(0, len(massage)):
encrypt = encrypt + chr(ord(massage[i]) ^ key)
print encrypt
say I give "yo yo" to it
it will give me :
,
,:
,:u
,:u,
,:u,:
I only need the final answer which is the ,:u,:
what do i have to do?
Put the print statement outside the loop.
Since the print statement is inside, it is running once per iteration. If it is outside, then it will only do it one time-- once it has finished.
for i in range(0, len(massage)):
encrypt = encrypt + chr(ord(massage[i]) ^ key)
print encrypt
Move the print statement outside the for loop. To do that you need to unindent the print statement.
unindent the call to print. This will take it out of the for loop and only print its value when the loop is finished.
On a slightly different note, you might want to work on your acceptance rate if you want people to put time and effort into answering your questions. You've asked 8 questions so far and you haven't accepted an answer to any of them. (Click the arrow next to an answer to accept it)
message= raw_input("Enter message to be encrypted: ")
spec = chr(0b1010101)
key = ord(spec)
encrypt = ""
for i in range(0, len(message)):
encrypt = encrypt + chr(ord(message[i]) ^ key)
print encrypt
Using a generator:
message= raw_input("Enter message to be encrypted: ")
key=0b1010101
print ''.join(chr(key^ord(c)) for c in message)

Categories