|
| 1 | +import nltk |
| 2 | +nltk.download('words') |
| 3 | +from nltk.corpus import words |
| 4 | + |
| 5 | +def find_anagrams(search_words, word_list): |
| 6 | + # Function to sort letters in a word and return it as a string |
| 7 | + def sort_word(word): |
| 8 | + return ''.join(sorted(word)) |
| 9 | + |
| 10 | + # Create a dictionary to store anagrams |
| 11 | + anagrams = {} |
| 12 | + |
| 13 | + # Group words based on their sorted letter representations |
| 14 | + for w in word_list: |
| 15 | + sorted_word = sort_word(w) |
| 16 | + if sorted_word in anagrams: |
| 17 | + anagrams[sorted_word].append(w) |
| 18 | + else: |
| 19 | + anagrams[sorted_word] = [w] |
| 20 | + |
| 21 | + results = {} |
| 22 | + |
| 23 | + # Find anagrams for each search word |
| 24 | + for search_word in search_words: |
| 25 | + sorted_word = sort_word(search_word) |
| 26 | + if sorted_word in anagrams: |
| 27 | + results[search_word] = anagrams[sorted_word] |
| 28 | + else: |
| 29 | + results[search_word] = [] |
| 30 | + |
| 31 | + return results |
| 32 | + |
| 33 | +if __name__ == "__main__": |
| 34 | + # Retrieve the NLTK word list |
| 35 | + nltk_word_list = words.words() |
| 36 | + |
| 37 | + # Sample search words |
| 38 | + search_words = ["silent", "debit card", "funeral", "astronomer"] |
| 39 | + |
| 40 | + # Combine the NLTK word list with the existing word list |
| 41 | + word_list = [ |
| 42 | + "listen", "silent", "enlist", "tinsel", "hello", "world", "python", |
| 43 | + "astronomer", "moonstarer", "debit card", "bad credit", "punishments", "nine thumps", |
| 44 | + "dormitory", "dirty room", "the eyes", "they see", "a gentleman", "elegant man", |
| 45 | + "funeral", "real fun", "slot machines", "cash lost in me", "eleven plus two", "twelve plus one" |
| 46 | + ] + nltk_word_list |
| 47 | + |
| 48 | + results = find_anagrams(search_words, word_list) |
| 49 | + |
| 50 | + for search_word, anagrams in results.items(): |
| 51 | + if anagrams: |
| 52 | + print(f"Anagrams of '{search_word}': {', '.join(anagrams)}") |
| 53 | + else: |
| 54 | + print(f"No anagrams found for '{search_word}'.") |
0 commit comments