why is it not accepting the hidden word? - python

i created a function that takes in a word and checks it in a file containing all words from the dictionary , accepts the word if it is found else it prints an error message and ask for the word again
def getHiddenWord():
file = open('dictionary.txt')
found = False
while found == False:
hiddenWord = input('Enter the hidden word')
for word in file.readlines():
if word.strip().lower() == hiddenWord.lower():
found = True
return hiddenWord.lower()
break
else:
continue
print('I don\'t have this word in my dictionary please try another word')
if i wrote a correct word in the first input it works perfectly but and time after that it keeps looping as intended but it doesn't accept the input taking in consideration that if i wrote the same words the first input it will work and get accepted

file.readlines()
can be called only once, when you'll try to call it again on the same opened file it will fail.
Solution: before the loop read the lines and save them into a variable:
def getHiddenWord():
file = open('dictionary.txt')
lines = file.readlines() # <-- here
file.close() # <-- here
found = False
while found == False:
hiddenWord = input('Enter the hidden word')
for word in lines: # <-- and here
if word.strip().lower() == hiddenWord.lower():
found = True
print(hiddenWord.lower() + ' found!') # <-- here
break
else:
print('I don\'t have this word in my dictionary please try another word')
Further, as Óscar López mentioned in his (now deleted) answer: if you want the game to continue after a word was found you shouldn't return - just print "success" and break

A better way would be to convert the file into a set once and the just use in to check if the input is there:
def get_hidden_word():
with open('dictionary.txt') as fp:
words = set(w.strip().lower() for w in fp)
while True:
guess = input('Enter the hidden word').strip().lower()
if guess in words:
return guess
print("I don't have this word in my dictionary please try another word")

Related

word Isn't equal to wordlist.readline() even though it is

Here's my code:
wordlist = open('words.txt')
word = input()
i = 0
def loop():
for i in range(466549):
if wordlist.readline().strip() == word:
print(f'found in {i}')
return
else:
print(f"not {wordlist.readline()}")
i = i + 1
loop()
Not only does it not return the first value of the list, but it also doesn't say that it found my word when it did. I got my words.txt file from GitHub, and the second word is "1080". But when I put that in, it prints 'not 1080' even though it clearly is.
I think what you are looking for is:
word = input("enter word: ").strip()
def loop():
with open("words.txt") as f:
wordList = f.readlines()
for i,line in enumerate(wordList):
line = line.strip()
if line == word:
print(f"found in line {i}")
return
else:
print(f"did not find in {line}")
loop()
or if you want to stick to using just readline:
word = input("enter word: ").strip()
wordList = open("words.txt")
def loop():
for i in range(466549):
line = wordList.readline().strip()
if line == word:
print(f"found in line {i}")
return
else:
print(f"did not find in {line}")
loop()
wordList.close()
Maybe you wanna find if specific word in text file.
First, wordlist.readline() actually reads a line from file which means it is not reproducible. so, print(f"not {wordlist.readline()}") doesn't work as you expected.
For example, let's say words.txt looks like below.
hello
1080
world
When you read first line with if wordlist.readline() ... inside loop, that value is "hello", and this is not 1080, so else statement runs. At here, you reads a line with print(f"not {wordlist.readline()}") as second which is 1080, thus not 1080 gonna be printed.
And finally, if wordlist.readline() ... will read world from file, this is also not 1080, and next readline() will be None.
Secondary problem is that variable i is not utilized properly. i is incremented automatically thanks to range and for keyword (Strictly, it just next value from iterable object, not increment), so you don't need like i = 0 or i = i + 1
Third thing is derived from the problem pointed in first one, which is None.strip() is impossible so it will raise an exception.
There are more things to say, but I'll just show you my example so you can compare it with yours
input_wordlist = open('words.txt')
input_word = input()
def loop(word, wordlist):
for index, line in enumerate(wordlist.readlines()):
if line.strip() == word:
# or if you wanna know whether word is in line
# if word in line:
print(f"found in {index}")
return
else:
print(f"not in {line}")
loop(input_word, input_wordlist)
input_wordlist.close()

Counting a desired word in a text file

I have to count the number of times a given word appears in a given text file, this one being the Gettysburg Address. For some reason, it is not counting my input of 'nation' so the output looks as such:
'nation' is found 0 times in the file gettysburg.txt
Here is the code I have currently, could someone point out what I am doing incorrectly?
fname = input("Enter a file name to process:")
find = input("Enter a word to search for:")
text = open(fname, 'r').read()
def processone():
if text is not None:
words = text.lower().split()
return words
else:
return None
def count_word(tokens, token):
count = 0
for element in tokens:
word = element.replace(",", " ")
word = word.replace("."," ")
if word == token:
count += 1
return count
words = processone()
word = find
frequency = count_word(words, word)
print("'"+find+"'", "is found", str(frequency), "times in the file", fname)
My first function splits the file into a string and turns all letters in it lower case. The second one removes the punctuation and is supposed to count the word given in the input.
Taking my first coding class, if you see more flaws in my coding or improvements that could be made, as well as helping find the solution to my problem, feel free.
In the for loop in the count_word() function, you have a return statement at the end of the loop, which exits the function immediately, after only one loop iteration.
You probably want to move the return statement to be outside of the for loop.
as a starter I would suggest you to use print statements and see what variables are printing, that helps to breakdown the problem. For example, print word was showing only first word from the file, which would have explained the problem in your code.
def count_word(tokens, token):
count = 0
for element in tokens:
word = element.replace(",", " ")
word = word.replace("."," ")
print (word)
if word == token:
count += 1
return count
Enter a file name to process:gettysburg.txt
Enter a word to search for:nation
fourscore
'nation' is found 0 times in the file gettysburg.txt
Use code below:
fname = input("Enter a file name to process:")
find = input("Enter a word to search for:")
text = open(fname, 'r').read()
def processone():
if text is not None:
words = text.lower().split()
return words
else:
return None
def count_word(tokens, token):
count = 0
for element in tokens:
word = element.replace(",", " ")
word = word.replace("."," ")
if word == token:
count += 1
return count
words = processone()
word = find
frequency = count_word(words, word)
print("'"+find+"'", "is found", str(frequency), "times in the file", fname)
statement "return" go out statement "for"

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()

Python 3.3: Output of Anagram Function

def anagram(word,check):
for letter in word:
if letter in check:
check = check.replace(letter, '')
else:
return 0
return 1
while True:
f = open('dictionary.txt', 'r')
try:
user_input = input('Word? ')
for word in f:
word = word.strip()
if len(word)==len(user_input):
if word == user_input:
continue
elif anagram(word, input):
print (word)
#try:
#if word == 1:
#print ('The only anagram for', user_input, 'is', word)
#elif word > 1:
#print ('The anagrams for', user_input, 'are', word)
#except TypeError:
#pass
except EOFError:
break
f.close()
The function works as I want it to, but I need some help with the output. I want the output in one line, and the wording should reflect the amount of anagrams found. (i.e. 'only one anagram', 'the anagrams are', 'there are no anagrams', or 'the word is not in the dictionary') The comments in the code are what I have tried. Thanks for any help.
The way I understand your program, you want to continuously prompt the user for words until he presses Ctrl-D (which results in an EOF error and breaks the loop)? In that case, you should read the file only once, before the beginning of the loop, and construct a list or set of the words in it. Also, your try/except statement should only contain the call to input as this is the only place where this exception can occur in your function.
Now on to your main question - to count the number of results and print different statements accordingly, just use a list comprehension to get a list of all anagrams of the input. Then you can count the anagrams and join them together to form an output string.
def find_anagrams():
with open("dictionary.txt", "r") as fileInput:
words = set(word.strip() for word in fileInput)
while True:
try:
user_input = input("Word? ").strip()
except:
break #you probably don't care for the type of exception here
anagrams = [word for word in words if anagram(word, user_input)]
print_results(anagrams)
def print_results(anagrams):
if len(anagrams) == 0:
print("there are no anagrams")
elif len(anagrams) == 1:
print("the only anagram is %s" % anagrams[0])
else:
print("there are %s anagrams: %s" % (len(anagrams), ', '.join(anagrams)))
The only thing missing from this code is cheking that the input word is not a part of the result list, but this can be moved to the anagram function. The function can also be simplified using the Counter class from the built-in collections module. This class is a dictionary-like object that can be constructed from an iterable and maps each object in the iterable to the number of its occurrences:
>>> Counter("hello") == {"h":1, "e":1, "l":2, "o": 1}
True
So we can rewrite the anagram function like this:
from collections import Counter
def anagram(word, check):
return not word == check and Counter(word) == Counter(check)
you can create a list with your results like this:
with open("dictionary.txt", "r") as fileInput:
user_input = input("Search keyword: ").strip()
listAnagrams = []
for line in fileInput.readlines():
for word in line.split(" "):
if len(word) == len(user_input):
if word == user_input:
continue
elif anagram(word, user_input):
listAnagrams.append(word)
if len(listAnagrams) == 1:
print ('The only anagram for', user_input, 'is', listAnagrams[0])
elif len(listAnagrams) > 1:
print ('The anagrams for', user_input, 'are', ", ".join(listAnagrams))
else:
print ('No anagrams found for', user_input)

Categories

Resources