简体   繁体   中英

How to check if a word exists in a text file using Python 3.3

The program is used to find anagrams for a inputted string. The possible anagrams come from a text file 'dict.txt'. However, I am trying to check if the inputted string is not in the dictionary. If the inputted string is not the dictionary, the program should not look for anagrams, and just print a message saying that the inputted string is not in the dictionary. Currently the code is saying that all of my inputted strings are not in the dictionary, which is incorrect.

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

Read all of your words into a list beforehand:

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

    for line in handle:
        word_list.append(line)

Replace for word in f with for word in word_list in your code, as now you have a list of all of the lines in the file.

Now, you can check if a word is in the list:

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

The with syntax lets you cleanly open a file without having to close it later one. Once you exit the scope of the with statement, the file automatically gets closed for you.


Also, you can simplify your anagram code a little bit:

def anagram(word, checkword):
    return sorted(word) == sorted(checkword)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM