该程序用于查找输入字符串的字谜。可能的字谜来自文本文件“dict.txt”。但是,我正在尝试检查输入的字符串是否不在字典中。如果输入的字符串不是字典,则程序不应该查找字谜,而只是打印一条消息,说明输入的字符串不在字典中。目前代码说我输入的所有字符串都不在字典中,这是不正确的。
def anagram(word,checkword):
for letter in word:
if letter in checkword:
checkword = checkword.replace(letter, '')
else:
return False
return True
def print_anagram_list():
if len(word_list) == 2:
print ('The anagrams for', inputted_word, 'are', (' and '.join(word_list)))
elif len(word_list) > 2:
print ('The anagrams for', inputted_word, 'are', (', '.join(word_list[:-1]))+ ' and ' +(word_list[-1]))
elif len(word_list) == 0:
print ('There are no anagrams for', inputted_word)
elif len(word_list) == 1:
print ('The only anagram for', inputted_word, 'is', (''.join(word_list)))
def anagram_finder():
for line in f:
word = line.strip()
if len(word)==len(inputted_word):
if word == inputted_word:
continue
elif anagram(word, inputted_word):
word_list.append(word)
print_anagram_list()
def check(wordcheck):
if wordcheck not in f:
print('The word', wordcheck, 'is not in the dictionary')
while True:
try:
f = open('dict.txt', 'r')
word_list=[]
inputted_word = input('Your word? ').lower()
check(inputted_word)
anagram_finder()
except EOFError:
break
except KeyboardInterrupt:
break
f.close()