0

该程序用于查找输入字符串的字谜。可能的字谜来自文本文件“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()
4

1 回答 1

0

事先将所有单词读入列表:

with open('dict.txt', 'r') as handle:
    word_list = []

    for line in handle:
        word_list.append(line)

在您的代码中替换for word in ffor word in word_list,因为现在您拥有文件中所有行的列表。

现在,您可以检查一个单词是否在列表中:

def check(wordcheck):
    if wordcheck not in word_list:
        print('The word', wordcheck, 'is not in the dictionary')

with语法使您可以干净地打开文件,而不必稍后再关闭它。退出with语句范围后,文件会自动为您关闭。


此外,您可以稍微简化字谜代码:

def anagram(word, checkword):
    return sorted(word) == sorted(checkword)
于 2012-12-08T05:58:05.107 回答