Python 3 dictionary.get() function not working with sys.stdin - python

I am currently writing a dictionary program that allows the user to enter in two words: an English word and its foreign translation. Then, the user should be able to input a foreign word and retrieve the English word; however, I am required to use sys.stdin for the second half.
import sys
dictionary = dict()
userInput = input()
while userInput != "":
buf = userInput.split()
english = buf[0]
foreign = buf[1]
dictionary[foreign] = english
userInput = input()
for userInput in sys.stdin:
print(type(userInput))
if userInput in dictionary:
print(dictionary.get(userInput))
else:
print("Word not in dictionary.")
When I use sys.stdin, the dictionary.get() function is not functioning properly. When I simply use the normal input() function instead of sys.stdin, the dictionary is able to function properly. Why is this and how can I get sys.stdin to properly work with the dictionary search?
This code seems to work, but once again... it used input() instead of sys.stdin:
import sys
dictionary = dict()
userInput = input()
while userInput != "":
buf = userInput.split()
english = buf[0]
foreign = buf[1]
dictionary[foreign] = english
userInput = input()
userInput = input()
while userInput != "":
if userInput in dictionary:
print(dictionary.get(userInput))
else:
print("Word not in dictionary")
userInput = input()
Thanks!

A trailing '\n' was the issue. string = string.rstrip('\n') fixed this for me.

Related

Need Guidance with some Python code (Substitute Cypher Python)

I have some code already but I got feedback on how to pass the rest of the criteria but I have no idea how to do it.
Assignment brief:
You are working in a Newspaper office that handles the reports from their journalists. You have been asked to design a program that will be used to help them send confidential reports in that others cannot read as email is not secure, we need to generate an encryption key that they can encode their scoops and documents when sent by email.
The program will need to generate the key. Encode the message, export the key, import a key from another person and decode a message. It will be a simple substitution cipher. The key needs to be made up out of all Alphanumeric Characters and some Special Characters. It will be a single key per session so you will need to save the key if you close the program otherwise you won’t be able to decode those messages used to encode them.
All projects start with planning it is the most important part that can make or break a project so ensure this is carried out correctly
Pass, Merit and Distinction Requirements
What the feedback says to do:
You were asked to import a key and export a key your program doesn't allow this so you would need to resubmit to get Pass4 and Pass6
Code I have done so far below
def run():
x=input("code or decode? ")
if x == "code":
a=list("")
import string
alpha = str("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
message=input("What is your message to encode? ")
x=len(message)
y=0
z=0
for counter in range(x):
y=y+1
letter = alpha.find(message[z:y])
z=z+1
letter=letter+13
if letter > 24:
letter=letter-24
letter=alpha[letter:letter+1]
if counter != x-1:
print(letter,end="")
else:
print(letter)
x=input("type yes to go again? ")
if x == "yes":
run()
else:
input()
else:
a=list("")
import string
alpha = str("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
message=input("What is your message to decode? ")
x=len(message)
y=0
z=0
for counter in range(x):
y=y+1
letter = alpha.find(message[z:y])
z=z+1
letter=letter-13
if letter < 0:
letter=24+letter
letter=alpha[letter:letter+1]
if counter != x-1:
print(letter,end="")
else:
print(letter)
x=input("again? ")
if x == "yes":
run()
else:
input()
run()
I did some research and come up with this.
You can use it as it is or edit it to meet your needs. Hope it helps.
Update.1: The longer the message, the bigger the encryption key will be. One solution for this is to use zlib.compress method in order to shrink the key, and then decompress it when needed.
Update.2: Added the export/import functionality of the encryption key using a Json file (you can of course choose other way of storing data) along with a title assigned to it, so you have the choice to either enter the title or enter the encryption key of the message for decryption. The title is just optional and for simplicity purposes, you can get rid of it if you want to. You'll also notice the code contains lots of if/else statements, that's just so you know where you currently are and what choices you have.
A GUI based would be better.
import string
import json
import os
# A list containing all characters
alpha = string.ascii_letters
def code(title, message, key = 6):
temp_dict = {}
cipher=[]
for i in range(len(alpha)):
temp_dict[alpha [i]] = alpha [(i+key)%len(alpha )]
# Generating the encryption key
for char in message:
if char in alpha :
temp = temp_dict[char]
cipher.append(temp)
else:
temp =char
cipher.append(temp)
# This code is needed to decode the expected message so make sure to save it by any method you want,
# otherwhise it'll generate a random text.
cipher= "".join(cipher)
main_data = {title : cipher}
file_name = "encryption_key.json"
if os.path.exists(file_name):
with open(file_name, "r+") as file:
data = json.load(file)
data[0].update(main_data)
file.seek(0)
json.dump(data, file)
else:
with open(file_name, "w") as file:
json.dump([main_data], file)
print("Encryption code :",cipher)
def decode(cipher, key = 6):
temp_dict = {}
for i in range(len(alpha)):
temp_dict[alpha [i]] = alpha [(i-key)%(len(alpha ))]
# Decoding the message
decoded_text = []
for char in cipher:
if char in alpha :
temp = temp_dict[char]
decoded_text.append(temp)
else:
temp = char
decoded_text.append(temp)
decoded_text = "".join(decoded_text)
return decoded_text
while True:
# There is an optional parameter (key) within the function which you can change according to your preference.
# The default value is 5 and it needs to be the same in both encode and decodefunctions.
x=input('[E]ncode or [D]ecode? answer with "e/d:" ')
if x.lower() == "e":
title = input("Enter the title of the message: ")
message = input("What is your message to encode? ")
code(title, message)
break
elif x.lower() == "d":
file_name = "encryption_key.json"
if os.path.exists(file_name):
with open(file_name, "r+") as file:
data = json.load(file)[0]
else:
print("There is no related file for decryption.")
continue
choice = input('Enter the [T]itle or the [K]ey of the message for decryption. [A]ll to decrypt everything on the file. answer with "t/k/a:" ')
if choice.lower() == 't':
title = input("Enter the title: ")
if title in data.keys():
encryption_key = data[title]
print(decode(encryption_key))
break
else:
print("There is no such title.")
elif choice.lower() == "k":
encryption_key = input("Enter the encryption code related to the message? ")
if encryption_key in data.values():
print(decode(encryption_key))
break
else:
print("There is no such encryption key.")
elif choice.lower() == "a":
decrypt_dict = {}
for k, v in data.items():
decrypt_dict[k] = decode(v)
print(decrypt_dict)
break
else:
print("There is no related file for decryption.")
else:
print("Enter a valid answer.")

How do I check if an input value is a valid string?

So I'm making a game of hangman and it starts with a "BotMaster" entering a string and then how many guesses that player will have to try and guess the string. I only just started and I'm trying to write a function that will check if what the BotMaster put is a valid string. A valid string would be a string that is only letters, no symbols, numbers, or extra spaces. I already have the functions that will remove extra spaces, and non-alpha inputs (So it takes out periods, extra spaces and such) and a function that makes it all lower case, but my function breaks if I enter a number an empty string. How should I add these?
#Imports (this is for later code I haven't written)
import os,time,random
#Removes extra spaces from the function
def space_cull(the_str):
result = the_str
result = result.strip()
result =" ".join(result.split())
the_str = result
return the_str
#Makes the string lowercase
def make_lower(the_str):
the_str = the_str.lower()
return the_str
#Checks if everything in the string are Alpha Inputs
def check_alpha(the_str):
the_str =''.join([char for char in the_str if char.isalnum()])
return the_str
#Ask Botmaster the string they want
def ask_bot():
while True:
bot_str = input('Enter a string for the player to guess: ')
bot_str = space_cull(bot_str)
bot_str = make_lower(bot_str)
bot_str = check_alpha(bot_str)
if bot_str == '':
print('That is not a correct string, try again')
True
return bot_str
ask_bot()
I added the ask_bot() part so I can test the function faster
This is what happens:
Enter a string for the player to guess: 1
#nothing
#Tested again:
Enter a string for the player to guess: ''
That is not a correct string, try again.
#But then exits the loop, which I don't want it to, if the string is wrong I want it to ask them again.
#Tested Again
Enter a string for the player to guess: 'Katze'
#Nothing, which is actually good this time
How do I fix this?
Your while loop will always terminate in the function as it is written.
def ask_bot():
while True:
bot_str = input('Enter a string for the player to guess: ')
bot_str = space_cull(bot_str)
bot_str = make_lower(bot_str)
bot_str = check_alpha(bot_str)
if bot_str == '':
print('That is not a correct string, try again')
True # <- this does nothing
return bot_str # < - this breaks out of the function and the loop
Your code edited to work:
def ask_bot():
while True:
bot_str = input('Enter a string for the player to guess: ')
bot_str = space_cull(bot_str)
bot_str = make_lower(bot_str)
bot_str = check_alpha(bot_str)
if bot_str == '':
print('That is not a correct string, try again')
else: # returns the string if the input is correct
return bot_str # this still breaks out of the function and the loop
# but only if the string has passed the checks
As other answers already mention, you could use str.isalpha() to check that the string is valid, or if you would like to modify the string in place you will need to adjust your check_alpha function like so:
def check_alpha(the_str):
the_str =''.join([char for char in the_str if char.isalpha()])
return the_str
As John Gordon already mentioned the solution is the method "isalpha" of the "str" class.
userInput = input("Your suggestion: ")
if userInput.isalpha():
# do some magic
else:
print("please only type in letters")
You don't need the check_alpha(str) function at all. Modify the ask_bot() as follows.
def ask_bot():
while True:
bot_str = input('Enter a string for the player to guess: ')
bot_str = space_cull(bot_str)
bot_str = make_lower(bot_str)
if not bot_str.isalpha():
if bot_str.isnum():
print("The entered string is a number")
continue
if bot_str == '':
print('That is not a correct string, try again')
continue
continue
break
return bot_str
ask_bot()

'AttributeError:' when I try to unpickle dictionary

I have made a program on python 3.5 which you can find out the password linked to a username, make a new password for an existing user and add a new user and password to the dictionary then pickles it so every time I load the program all the usernames and passwords will be there.
The error that comes up is after you create the pickle file(after running it for the first time) then on line 6 the error
AttributeError: Can't get attribute 'NewPass' on <module '__main__' (built-in)>
occurs.
Here is my script:
import sys
import pickle
import os
if os.path.exists("branston.p"):
LOGG = pickle.load(open('branston.p', 'rb'))
else:
LOGG = {'Sam': ('CHRIST')}
def Find():
Username = input("Say a Username.")
print (LOGG[Username])
def NewPass():
Username = Input("Enter your username.")
Newpass = input("Enter your new password")
if NewPass == input("Confirm password"):
LOGG[Username] = (NewPass)
def NewEntry():
NewUser = input("Enter your new username.")
Newpass = input("Enter your new password.")
LOGG[NewUser] = (NewPass)
loop = True
while loop == True:
function = input("Say what you want me to do.'Find', 'NewPass', 'NewEntry', 'Stop'.")
if function == ("Find"):
Find()
elif function == ("NewPass"):
NewPass()
elif function == ("NewEntry"):
NewEntry()
elif function == ("Stop"):
f = open('branston.p', 'wb')
pickle.dump(LOGG, f)
f.close()
sys.exit()
Any help would be appreciated. Thanks!
When you do this
LOGG[NewUser] = (NewPass)
You are assigning the function NewPass to your dict entry. You are probably intending to assign the password string and therefore it should be.
LOGG[NewUser] = Newpass
Note: Parenthesis are superfluous. I'd also suggest avoiding using upper case letters as the first character of your variable names, as otherwise it is easy to confuse variable and function names.

Python - Word Scramble Game

While this assignment is past due (I joined the class late unfortunately) I still need to figure it out. I have the following list of words:
abhor:hate
bigot:narrow-minded, prejudiced person
counterfeit:fake; false
enfranchise:give voting rights
hamper:hinder; obstruct
kindle:to start a fire
noxious:harmful; poisonous; lethal
placid:calm; peaceful
remuneration:payment for work done
talisman:lucky charm
abrasive:rough; coarse; harsh
bilk:cheat; defraud
I need to read this file into a dictionary, pick a random key, scramble it, then ask the user to solve it. Unlike other solutions on here, it does not iterate three times, but runs until the user enters 'n'. The code will ask the user after each round if the user wants to continue the game. The user can also type 'hint' to get the definition of the word.
There is a similar question here: (http://www.dreamincode.net/forums/topic/302146-python-school-project-write-a-word-scramble-game-status-complete/) or rather the result of a question, but I am not knowledgeable enough to bridge the gaps and make it work for my purposes. None of the variation on this that I have seen on stack overflow come close enough for me to bridge the gap either, likely because I just don't know enough yet. Before we even start, this code does not yet work at all really, I am pretty lost at this point, so please be gentle. My code so far is below:
import random
from random import shuffle
#Reads the words.txt file into a dictionary with keys and definitions
myfile = open("words.txt", "r")
wordDict = dict([(line[:line.index(":")], line[line.index(":") +1 : -1])
for line in myfile.readlines()])
#print (b)
def intro():
print('Welcome to the scramble game\n')
print('I will show you a scrambled word, and you will have to guess the word\n')
print('If you need a hint, type "Hint"\n')
#Picks a random key from the dictionary b
def shuffle_word():
wordKey = random.choice(list(wordDict.keys()))
return wordKey
#Gives a hint to the user
def giveHint(wordKey):
hint = wordDict[wordKey]
return hint
#Below - Retrieves answer from user, rejects it if the answer is not alpha
def getAnswer():
answer = input('\nEnter your first guess: ')
while True:
if answer.isalpha():
return answer
else:
answer = input('\nPlease enter a letter: ')
def keepPlaying():
iContinue = input("\nWould you like to continue? ")
return iContinue
def scramble():
theList = list(shuffle_word())
random.shuffle(theList)
return(''.join(theList))
#Main Program
if keepPlaying() == 'y':
intro()
shuffle_word()
randomW = shuffle_word()
#scramKey = list(randomW)
thisWord = scramble()
print ("\nThe scrambled word is " +thisWord)
solution = getAnswer()
if solution == thisWord:
print("\nCongratulations")
if solution == 'Hint' or solution == 'hint':
myHint = giveHint(wordKey)
print(myHint)
else:
print("\nThanks for playing")
I have edited this post to ask for new information, though I am not sure if that ishow its properly done. Thanks to the help of those below, I have made progress, but am stuck not on a specific piece.
I have two questions. 1: How can I get the giveHint() function to return the definition of the random key selected by the shuffle_wprd() function. I know what I have above will not work because it is simply returning a string, but it seems like just using a dict.get() function would not get the correct definition for the random word chosen.
2: How can I get the program not to ask the user to continue on the first pass, but to then ask from then on. I thought about using a while loop and redefining the variable during the iteration, but I don't know enough to get it to work properly.
regardless, thank you to those people who have already helped me.
This should help you out a bit, the length seems to be of no benefit as a hint as you can see the length of the scrambled word so I used the definition as the hint,I think you also want to ask the user to guess the word not individual letters:
from random import shuffle, choice
#Reads the words.txt file into a dictionary with keys and definitions
with open("words.txt") as f:
word_dict = {}
for line in f:
# split into two parts, word and description
word, hint = line.split(":")
word_dict[word] = hint
def intro():
print('Welcome to the scramble game\n')
print('I will show you a scrambled word, and you will have to guess the word\n')
#Picks a random key from the dictionary b
def pick_word():
word = choice(list(word_dict.keys()))
return word
#Gives a hint to the user
def give_hint(word):
# return the definition of the word
descrip = word_dict[word]
return descrip
#Below - Retrieves answer from user, rejects it if the answer is not alpha
def get_answer():
while True:
answer = input('Please enter a guess: ')
if answer.isalpha():
return answer
else:
print("Only letters in the word")
def main():
intro()
word = pick_word()
# give user lives/tries
tries = 3
shffled_word = list(word)
# shuffle the word
shuffle(shffled_word)
# rejoin shuffled word
shffled_word = "".join(shffled_word)
# keep going for three tries as most
while tries > 0:
inp = input("Your scrambled word is {}\nEnter h if you want to see your hint or any key to continue".format(shffled_word))
if inp == "h":
print("The word definition is {}".format(give_hint(word)))
ans = get_answer()
if ans == word:
print("Congratulations you win!")
break
tries -= 1
# ask user if they want to play again, restarting main if they do
play_again = input("Press 'y' to play again or any key to exit")
if play_again == "y":
main()
# else the user did not press y so say goodbye
print("Goodbye")
main()
There are a few more bits to be added but I will leave that up to you.
Thank you to all those who helped. For any who come along later, the final product is here. Similar to what Padraic Cunningham put, but without the three answer limit, and without his more elegant solution of wrapping the main program into a called function.
import random
from random import shuffle, choice
#Reads the words.txt file into a dictionary with keys and definitions
with open("words.txt") as f:
wordDict = {}
for line in f:
# split into two parts, word and description
word, hint = line.split(":")
wordDict[word] = hint
#print (b)
def intro():
print('Welcome to the scramble game\n')
print('I will show you a scrambled word, and you will have to guess the word\n')
print('If you need a hint, type "Hint"\n')
#Picks a random key from the dictionary b
def shuffle_word():
wordKey = choice(list(wordDict.keys()))
return wordKey
#Gives a hint to the user
def giveHint(wordKey):
descrip = wordDict[word]
return descrip
#Below - Retrieves answer from user, rejects it if the answer is not alpha
def getAnswer():
answer = input('\nEnter a guess: ')
while True:
if answer.isalpha():
return answer
else:
answer = input('\nPlease enter a letter: ')
def getAnswer2():
answer2 = input('\nEnter another guess: ')
while True:
if answer2.isalpha():
return answer2
else:
answer2 = input('\nPlease enter a letter: ')
def keepPlaying():
iContinue = input("\nWould you like to continue? ")
return iContinue
#def scramble():
# theList = list(shuffle_word())
# random.shuffle(theList)
# return(''.join(theList))
#Main Program
while keepPlaying() == 'y':
intro()
#shuffle_word()
randomW = shuffle_word()
cheatCode = giveHint(randomW)
#scramKey = list(randomW)
thisWord = list(randomW)
print(thisWord)
random.shuffle(thisWord)
print(thisWord)
thisRWord = ''.join(thisWord)
print ("\nThe scrambled word is " +thisRWord)
solution = getAnswer()
loopMe = False
while loopMe == False:
if solution == randomW:
print("\nCongratulations")
loopMe = True
if solution == 'Hint' or solution == 'hint':
print(cheatCode)
if solution != randomW:
loopMe = False
solution = getAnswer2()

Making a 'quiz-construction' with arrays

I'm building a simple 'quiz-program'. Code here:
import random
wordList1 = []
wordList2 = []
def wordAdd():
wordNew1 = str(input("Add a word to your wordlist: "))
wordNew2 = str(input("Add the translation to this word: "))
if wordNew1 != "exit":
wordList1.append(wordNew1)
wordAdd()
elif wordNew2 != "exit":
wordList2.append(wordNew2)
wordAdd()
else:
exercise()
def exercise():
q = random.choice(wordList1)
a = wordList2
if q[] == a[]:
print("Correct!")
else:
print("Wrong!")
wordAdd()
I'm trying to check the wordList1-number and compare it with the wordList2-number.
Now I didn't expect the def exercise to work but I can't find the solution to let it work...
I know about the dictionary-thing in Python but I would like to know wether such a array-construction is possible in Python.
Could someone help me with this?
Thanks in advance! Sytze
I played with your code a little. I'm not sure I perfectly understand your question, but I made it working the way I thought it needs to work. I added some comments to make it clear what I did.
I tried to stick with your basic concept (except the recursion), but I renamed a lot of things to make the code more readable.
import random
words = []
translations = []
def add_words():
# input word pairs until the user inputs "exit"
print('\nInput word and translation pairs. Type "exit" to finish.')
done = False
while not done:
word = raw_input("Add a word to your wordlist: ")
# only input translation, if the word wasn't exit
if word != "exit":
translation = raw_input("Add the translation to this word: ")
if word != "exit" and translation != "exit":
# append in pairs only
words.append(word)
translations.append(translation)
else:
done = True
def exercise():
# excercising until the user inputs "exit"
print("\nExcercising starts. ")
done = False
while not done:
# get a random index in the words
index = random.randrange(0, len(words))
# get the word and translation for the index
word = words[index]
translation = translations[index]
# ask the user
answer = raw_input('Enter the translation for "%s": ' % word)
if answer == "exit":
done = True
print("\nGoodbye!")
elif answer == translation:
print("Correct!")
else:
print("Wrong!")
add_words()
exercise()

Categories

Resources