##open file and create a dictionary of {"word":"sorted word"}
word_file = open("word_list(1).txt","r")
word_list = {}
for text in word_file:
simple_text = ''.join(sorted(text.lower().strip()))
word_list.update({text.lower().strip():simple_text})
##lowercase and sort the user input word
def simplify_entered_word():
lower_word = ''.join(sorted(input_word.lower().strip())) #Creates a list with the lowercase, sorted letters.
return lower_word
#Compare the sorted user input with the values of the dictionary to find the anagrams.
def find_in_dict(entered_word):
for key,val in word_list.items():
if val == entered_word:
print(key,input_word)
##main loop
while True:
input_word = input("Input the word for anagram checking: ")
find_in_dict(simplify_entered_word())
|
||||
|
Good that you tagged with Python 3, as it kinda works in Python 2.7 with a bit different behaviour. All the time reminder to format according to
PEP8; here I'd note that
there should be spaces between names, i.e. Firstly, it's good that there are functions to split the logic up. However part of that is negated by using globals. In general using globals is a bad pattern - here in particular it makes more sense to pass the word list through to the individual functions. Edit: And I forgot to update it to not use globals, shame on me ... Most of the comments can also be docstrings instead. Now, for the globals. Just pass them through to the functions:
This function can now also be reused easily by returning two results, the lowercased word and the sorted result. Next I'd move the word list reading its own function:
However this can also be much easier in terms of
N.b. there might be a better way to write that dictionary
comprehension. Note also that I used And then call that with the filename:
Just in case this will only run as a script and not if the file is imported somewhere else, which is good practice. One problem that still remains is the iteration in
Note the use of |
|||||
|