Now, I'm learning Python and I want to make a dictionary, where the user can add words (in first step just the word, later definition).
word = input('Write a word here')
print('You added ' + word)
So, what I would like is the user can add more word, and the program save it to other string.
How can I do this?
Typically, this could be done in a while-loop where the loop-condition variable is updated upon user input:
continue_condition = True
words = []
while continue_condition:
word = input("Write a word here")
words.append(word)
continue_condition = input("Would you like to add another word? Then please type `Y`") == "Y"
If you want to populate a dictionary instead of a list, just adapt this code to your specific needs.
this will help to automate:
dict = {} # variable to store the key and value
def add(): # add function to add more word in our dictionary.
word = input('enter the word: ') # take the user input
dict[word] = word; # this will add the word to our dict for simplicity this is sample so we are using the same key and value.
if('y' == input('do you want to add more word (y/n): ')): # check if user want to add more word to dictionary.
add() # if yes the call function again ---recursion.
add() # call function for add word for first time.
print(dict) # print all the words in our dict.
Related
So I have a small project with python.
A random song name and artist are chosen.
The artist and the first letter of each word in the song title are displayed.
The user has two chances to guess the name of the song.
If the user guesses the answer correctly the first time, they score 3 points. If the user guesses
the answer correctly the second time they score 1 point. The game repeats.
The game ends when a player guesses the song name incorrectly the second time.
So far I've created a text document and put a few lines of song titles.
In my code I have used the following:
random_lines = random.choice(open("songs.txt").readlines())
This randomly picks a line in the code and does nothing with it.
I am asking where I go from here. I need to display the first letters of each word on the line. I then need a counter or some sort to add chances. I also need to write something that will check to see if they have it correct and add to a score counter.
OK, now just continue with your plan, it's good. Now you have to get the first letter from each word in line. You can do that with:
res = []
for i in line.split():
res.append(i[0])
There you are, you have the first letter of every word in the list res. Now you need to check if the user entered the title correctly. Maybe the best idea would be to keep everything lower-cased (in your file and in the user input) for easier checking. Now you just have to transform the user input to lower-case. You can do it with:
user_entry = input('Song title:')
if user_entry.lower() == line.lower():
score += 3
else:
user_entry_2 = input('Song title:')
if user_entry_2.lower() == line.lower():
score += 1
else:
print('Game over.')
sys.exit()
You should make this into a function ad call it in a loop until user misses. The function could return the current score which you could print out (in that case you should remove sys.exit() call)
I hope this is clear enough. If not, write the question in the comments :)
Assuming your random choice string contains the data in the format {songname} - {artist}
Then you first need to get the song name and the artist as a separate strings.
Print the first letters and ask for input.
After which you need to compare the strings and do some logic with the points.
points = 0;
while(1):
random_line = 'Song - artist' #change this with your random string
song, artist = random_line.split('-')
print("{0} - {1}".format(song.strip()[:2], artist.strip()[:2]))
for i in range(0,3):
if (i == 2):
print('You died with {} points'.format(points))
exit(0)
elif(random_line.lower() == input('Gues the song: ').lower()):
points += 2 - i
print('correct guess. points: ' + str(points))
break
else:
print('Try again')
I'm looking for a resource to learning me how to connect TKinter and JSON
Like take an input value (word) and search for that word in JSON then print out the result of the search
by way, I have already the python application working through terminal but I want to go further step and build a GUI
Thank you,
import json #import the JSON module
from difflib import get_close_matches #difflib module provides classes and functions
#for comparing sequences
#get_close_matches Return a list of
#the best “good enough” matches
data = json.load(open("data.json")) #load JSON to python dictionary
def translate(w):
w = w.lower() #change the input to lower case
if w in data: #first scenario check if the word exist in the dictionary, if exist load the data
return data[w]
elif w.title() in data: #When the user inputs a proper noun
return data[w.title()] #returns the definition of names that start with a capital letter
elif w.upper() in data: #definition of acronyms
return data[w.upper()]
elif len(get_close_matches(w, data.keys())) > 0: #second scenario compare the word and get the best match
#ask the user if the result of matching what is looking for
YN = input("Did you mean %s instead? Enter y if yes or n if no:" % get_close_matches(w, data.keys())[0])
if YN == "y":
return data[get_close_matches(w, data.keys())[0]]
elif YN == "n":
return "The word doesn't exist. Please double check it."
else:
return "We didn't understand your entry."
#third scenario the word not match or can't found
else:
return "The word doesn't exsit. Please double check it."
word = input("Enter word: ")
#in some cases the word have more than one definition so we need to make the output more readable
output = translate(word)
if type(output) == list:
for item in output:
print(item)
else:
print(output)
Here's how to do it!
Sketch some pictures of what your current program would look like if it had a GUI.
Would "Did you mean %s instead?" be a popup box?
Would you have a list of all the known words?
Build the UI using tkinter.
Connect the UI up to the functions in your program. (You do have those, don't you?)
Your program isn't quite ready yet, since you are doing stuff like using input inside your functions. Rework it so that it makes sense to have these outside your functions, then it'll probably be ready.
how do i find a string or a list in a text file. If i have a text file filled with words only, random words, not sentences, how do i find a string inside it. lets say I take a user input, how do I test or check if the string input by the user exist in the text file.
so far i have this:
x = open('sample.txt')
for a in x:
b = a.split() #converts the string from the txt to a list
c = input('enter: ') #user input
if any(c in a for a in b):
print('yes')
want to make a simple spellchecker. so from the user input string i want to check if that string matches the strings/list in the txt file
You mean, how to find a word in this file? That's
with open("sample.txt") as input:
dictionary = set(input.read().split())
then
w in dictionary
for your word w.
You asked three related but different questions:
1. "how do i find a string or a list in a text file."
text = input('enter: ')
data = open("sample.txt").read()
position = data.find(text)
if position != -1:
print("Found at position", position)
else:
print("Not found")
2. "how do I test or check if the string input by the user exist in the text file"
text = input('enter: ')
data = open("sample.txt").read()
if text in data:
print("Found")
else:
print("Not found")
3. "I want to make a simple spellchecker. so from the user input string i want to check if that string matches the strings/list in the txt file"
Make a dictionary like this, globally in a module:
dictionary = open("sample.txt").read().split()
Then you use the dictionary by importing it:
from themodule import dictionary
And you check if a word is in the dictionary like so:
'word' in dictionary
The code I currently have is shown below. What it does first is ask the user to input a sentence. The program then finds the position of each word in the sentence and also splits the word into a list to get individual words. The program then gets rid of any repeated words to make the words in the list unique. The program then proceeds to save (using son)the position of words in the sentence (e.g 1,2,3,4,1,1,2,3,5) and unique words to a separate file (which the user can name). The next part of the program tries to decompress the unique text from the separate file and tries to recreate the original sentence from the position of words in the sentence and unique words. I know this stage works as I have tested it separately. However when i run the program now, I keep getting this error message:
File "/Users/Sid/Desktop/Task3New.py", line 70, in OutputDecompressed
decompression.append(orgwords[i])
IndexError: list index out of range
I have no idea why this isn't working, anyone care to help? All help appreciated, thanks.
import json
import os.path
def InputSentence():
global sentence
global words
sentence = input("Enter a sentence: ")
words = sentence.split(' ')
def Validation():
if sentence == (""):
print ("No sentence was inputted. \nPlease input a sentence...")
Error()
def Uniquewords():
print ("Words in the sentence: " + str(words))
for i in range(len(words)):
if words[i] not in unilist:
unilist.append(words[i])
print ("Unique words: " + str(unilist))
def PosText():
global find
global pos
find = dict((sentence, words.index(sentence)+1) for sentence in list(words))
pos = (list(map(lambda sentence: find [sentence], words)))
return (pos)
def OutputText():
print ("The positions of the word(s) in the sentence are: " + str(pos))
def SaveFile():
filename = input("We are now going to save the contents of this program into a new file. \nWhat would you like to call the new file? ")
newfile = open((filename)+'.txt', 'w')
json.dump([unilist, pos], newfile)
newfile.close
def InputFile():
global compfilename
compfilename = input("Please enter an existing compressed file to be decompressed: ")
def Validation2():
if compfilename == (""):
print ("Nothing was entered for the filename. Please re-enter a valid filename.")
Error()
if os.path.exists(filename + ".txt") == False:
print ("No such file exists. Please enter a valid existing file.")
Error()
def OutputDecompressed():
newfile = open((compfilename)+'.txt', 'r')
saveddata = json.load(newfile)
orgpos = saveddata[1]
orgwords = saveddata[0]
print ("Unique words in the original sentence: " + str(orgwords) + "\nPosition of words in the sentence: " + str(orgpos))
decompression = []
prev = orgpos[0]
x=0
#decomposing the index locations
for cur in range(1,len(orgpos)):
if (prev == orgpos[cur]): x+= 1
else:
orgpos[cur]-=x
x=0
prev = orgpos[cur]
#Getting the output
for i in orgpos:
decompression.append(orgwords[i-1])
finalsentence = (' '.join(decompression))
print ("Original sentence from file: " + finalsentence)
def Error():
MainCompression()
def MainCompression():
global unilist
unilist = []
InputSentence()
Uniquewords()
PosText()
OutputText()
SaveFile()
InputFile()
Validation()
OutputDecompressed()
MainCompression()
The problem is that you are using the indices form words as indices for unilist/orgwords.
Let's take a look at the problem:
def PosText():
global find
global pos
find = dict((sentence, words.index(sentence)+1) for sentence in list(words))
pos = (list(map(lambda sentence: find [sentence], words)))
return (pos)
Here find maps every word to its position in the list words. (BTW why is the variable that iterates over words called sentence?) Then, for every word this position is stored in a new list. This process could be expressed in one line: pos = [words.index(word)+1 for word in words]
When you now look at OutputDecompressed, you see:
for i in orgpos:
decompression.append(orgwords[i-1])
Here orgpos is pos and orgwords is the list of unique words. Now every stored index is used to get back the original words, but this is flawed because orgpos contains indices of words even though they are used to access orgwords.
The solution to this problem is to rewrite PosText and parts of OutputDecompressed:
def PosText():
global pos
pos = [unilist.index(word)+1 for word in words]
return pos
def OutputDecompressed():
newfile = open((compfilename)+'.txt', 'r')
saveddata = json.load(newfile)
orgpos = saveddata[1]
orgwords = saveddata[0]
print ("Unique words in the original sentence: " + str(orgwords) + "\nPosition of words in the sentence: " + str(orgpos))
decompression = []
# I could not figure out what this middle part was doing, so I left it out
for i in orgpos:
decompression.append(orgwords[i-1])
finalsentence = (' '.join(decompression))
print ("Original sentence from file: " + finalsentence)
Some comments on your code:
After InputSentence() Validation() should be called to validate it
After InputFile() you must call Validation2() and not Validation()
In Validation2() it should be compfilename and not filename
You should use parameters instead of global variables. This makes it more clear what the functions are supposed to do. For example Uniquewords could accept the list of words and return the list of unique words. It also makes the program much easier to debug by just testing every function one-by-one, which is currently not possible.
To make it easier for other Python programmers to read your code you could use the Python coding style specified in PEP 8
Here is my code:
dictionary = {'A':'3',
'B':'u',
'C':'t',
'D':'5',
'E':'b',
'F':'6',
'G':'7',
'H':'8',
'I':'/',
'J':'9',
'K':'0',
'L':'-',
'M':'o',
'N':'i',
'O':';',
'P':'}',
'Q':'c',
'R':'n',
'S':'4',
'T':'m',
'U':'.',
'V':'y',
'W':'v',
'X':'r',
'Y':',',
'Z':'e',
}
print(dictionary)
inp = input(str("What do you want me to encode?").upper()).upper()
li = list(inp)
print(li)
for letter in inp:
pass
I want to ask how I could use this dictionary to encrypt any message that goes through the input. Like 'Hello my name is Jerry' would turn into: (Without Phrasing) '8b--; o, i3ob /4 9bnn,'.
Could someone please help me with this. Ive seen other questions like this being asked - but they use PyCrypto. I dont want to go through the hassle of installing it. Could someone please help me.
Thanks,
Jerry
You need to pass each character of the user input through the dictionary to get the cypher value out.
# removed the first .upper() here
inp = input(str("What do you want me to encode?")).upper()
li = list(inp)
print(li)
# create a list of letters passed through the dictionary
out = [dictionary[letter] for letter in inp]
# using ''.join makes the new list a single string
print(''.join(out))
You can use the str.translate method. The benefit here is that you only have to create the table once, so you can use the same table even if you have lots of strings to encrypt.
table = str.maketrans(dictionary) # create a translate table
inp = input("What do you want me to encode? ").upper()
res = inp.translate(table)
print(res)