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)
Related
I am building hangman in python.
The first two functions I have generates random word and its definition from the API which is working just perfectly.
import requests
import json
def generate_random_word():
random_word_url = 'https://random-word-form.herokuapp.com/random/adjective'
random_word_url_response = requests.get(random_word_url)
return json.loads(random_word_url_response.text)[0]
def get_random_word_definition():
random_word = generate_random_word()
definition_api_url = 'https://api.dictionaryapi.dev/api/v2/entries/en/' + random_word
definition_api_url_response = requests.get(definition_api_url)
return json.loads(definition_api_url_response.text)[0]['meanings'][0]['definitions'][0]['definition'],random_word
My next function is this:
def modify_word(word):
new_word = list(word)
for i in range(len(new_word)):
new_word[i] = '_'
return "".join(new_word)
As you see it iterates other listed word and changes its characters to "_".
Now to the issue:
def validate_word(original,guess,hidden_word):
listify_original = list(original)
listify_hidden = list(hidden_word)
for char_place,char in enumerate(listify_original):
if(char == guess):
listify_hidden[char_place] = char
print('found it',"".join(listify_hidden))
This function is accepting 3 parameters: 1.Original word which was generated 2.Players guess 3.Hidden word which is generated through modify_word function above
Whenever user gets correct guess the hidden latter in string is replaced with this letter as expected so if the word is "colour" and user types c the function will print out string like this c_____ as it should. But issue comes when user guesses another latter. in this case whole string is being re-generated and letter guessed before last one just disappears. so for example if user guessed "l" function will print out __l___ instead of c__l___.
This is the main function in which I call validate_word:
def hang_man_guess_game():
generate_word = get_random_word_definition()
definition = generate_word[0]
word = generate_word[1]
amount_of_tries = 6
print('Welcome to the hang man game!')
print('The length of the word is: ',len(word))
print('The defition of word is: ',definition)
print('Amount of health: ',amount_of_tries)
print('Health gets lesser on each wrong guess!')
print('You can write as many latters as you want!')
print('Good luck player!')
hidden_word = modify_word(word)
while(amount_of_tries != 0):
print('Word: ', hidden_word)
user_guess = input('Enter your guess: ')
validate_word(word,user_guess,hidden_word)
# print('Good job')
hang_man_guess_game()
Sample input for word is: hopeful
Any suggestions please?
You are not updating hidden_word as the user guesses a letter right. You can do this by returning the updated value in validate_word()
def validate_word(original,guess,hidden_word):
listify_original = list(original)
listify_hidden = list(hidden_word)
current_word = hidden_word
for char_place,char in enumerate(listify_original):
if(char == guess):
listify_hidden[char_place] = char
current_word = "".join(listify_hidden)
print('Found it', current_word)
return current_word
Similarly in the while loop in hang_man_guess_game(), the returned value now becomes the updated hidden_word
while(amount_of_tries != 0):
print('Word: ', hidden_word)
user_guess = input('Enter your guess: ')
hidden_word = validate_word(word,user_guess,hidden_word)
Output
Enter your guess: q
Word: _____
Enter your guess: c
Found it c____
Word: c____
Enter your guess: r
Found it c___r
Word: c___r
Enter your guess: o
Found it co__r
Found it co_or
Word: co_or
Enter your guess: l
Found it color
Word: color
You should update your hidden_word with based on the function validate_word. You should return "".join(listify_hidden). You can then move you print function in the main, this is in my opinion good practice to make sure each function only has one task (i.e. validate the word and printing is another task).
In your validate_word function, the hidden_word variable is never modified. At the beginning, you create a new list, called listify_hidden, but when you change a letter in this variable, it does not propagate to the original hidden_word string, outside of the function.
One way to fix this would be to make your validate_word return the new hidden string, with the discovered letters.
So you'll have to make the function return the updated hidden word:
def validate_word(original,guess,hidden_word):
listify_original = list(original)
listify_hidden = list(hidden_word)
for char_place,char in enumerate(listify_original):
if(char == guess):
listify_hidden[char_place] = char
print('found it',"".join(listify_hidden)
)
return "".join(listify_hidden)
And then in your while loop:
while(amount_of_tries != 0):
print('Word: ', hidden_word)
user_guess = input('Enter your guess: ')
hidden_word = validate_word(word,user_guess,hidden_word) <-- update the hidden word
# print('Good job')
I want to print if the word appears, as well as how many times the word appears in the file. I can't get it to say anything other than this word appears 1 or 0 times in the file.
This problem occurs on line 26, print("It appears " + str(wordcount[word]) + " times")
specifically str(wordcount[word]). This probably simple question, but this is my first week of python so if anyone has an idea please share. Thanks!
I've tried putting wordcount[word], word_counter.__getitem__(wordcount[word]), and word_counter.__getitem__(wordcount)
import collections
file = open(r"C:\Users\Patrick Wu\Documents\1wordfreqtest.txt", "r")
if file.mode == "r":
contents = file.read()
word = input("Word to check for :")
wordcount = {}
"""this below is to remove difference between upper and lower cases as
well as punctuation"""
for word in contents.lower().split():
word = word.replace(".","")
word = word.replace(",","")
word = word.replace(":","")
word = word.replace("\"","")
word = word.replace("!","")
word = word.replace("“","")
word = word.replace("‘","")
word = word.replace("*","")
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
word_counter = collections.Counter(wordcount)
if word in str(contents):
print("This word is in the file :)")
print("It appears " + str(wordcount[word]) + " times")
else:
print("This word isn't in the file")
The variable word is overwritten in the local scope, by the loop. So your input word is overwritten by the loop and you end up checking the count of the last word of the input file. Change the input word to be a different variable name than the word you're iterating through in the file.
You have a scoping problem, by using the same name "word" both in the input and in the for-loop.
I would suggest doing something like this:
word = input("Word to check for :")
with open('your_file.txt') as f:
raw = f.read()
num_appearences = raw.count(word)
print(f"The word {word} appears {num_appearences} times in the file")
You can use this code:
import collections
file = open("wordfreqtest.txt", "r")
if file.mode == "r":
contents = file.read().lower()
word = input("Word to check for :").lower()
times = 0
finish = 0
while finish==0:
if word in contents:
contents = contents[contents.find(word) + len(word):]
times += 1
else:
break
if times > 0:
print("This word is in the file :)")
print("It appears " + str(times) + " times")
else:
print("This word isn't in the file")
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")
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"
My Code: (Python: v3.5.2)
import time
import sys
def Word_Position_Finder():
chosen_sentence = input("Make a simple sentence: ").upper()
print("")
print(chosen_sentence)
print("")
sentence_list = chosen_sentence.split()
if len(chosen_sentence) == 0:
print("Your sentence has no words.")
time.sleep(1)
Choose_To_Restart()
print(sentence_list)
print("")
time.sleep(1)
users_choice = input("Press '1' to make a new sentence or press '2' keep current sentence: ")
print("")
if users_choice == "1":
print("Restarting Program.")
time.sleep(1)
Restarting_Program()
elif users_choice == "2":
print("")
print("'" + chosen_sentence + "'" + " --- " + "Is your current sentence.")
print("")
time.sleep(1)
position = []
for word in sentence_list:
postions = position.append(sentence_list.index(word) + 1)
print(position)
with open("Positions.txt", "w") as text_file:
print(chosen_sentence, position)
else:
print("That isn't a valid answer")
Choose_To_Restart()
What the code is trying to achieve:
The code above takes a sentence of the users choice, makes that sentence into a list and then prints the position of each of those words in that list and then is meant to save the user's sentence and the positions of the user's sentence into a simple .txt file.
Question:
How do I make my code create .txt file that saves the user's sentence and the positions of each word in the user's sentence into that .txt file?
The current problem I am having with the code is that the code does create a .txt file but nothing is saved in that file.
Iterate over the list containing the words of sentence. For each word, check that whether it exists in the other list containing words for finding the positions. Use collections.defaultdict to store the index of each word. Below is the sample code:
from collections import defaultdict
my_sentence = 'this is my sentence where this content is supposed to be checked'
sentence_words = my_sentence.split()
my_dict = defaultdict(list)
for i, item in enumerate(sentence_words):
my_dict[item].append(i)
# content of 'my_dict':
# {'this': [0, 5], 'is': [1, 7], 'where': [4]}
Refer Python Print String To Text File regarding how to write content to a a file.