Search code examples
pythonpython-3.xpython-requestsdictionary-comprehensionanagram

Python Question Relating to Finding Anagram from Dictionary


I am struggling with this project that I am working on.

Edit: I want the program to find 2 words from the dictionary that are the anagram of the input word(s). The way I wanted to approach this program is by using counter(input()) and then looping through the dictionary content twice (finding first word anagram then the next). The loop would take every word from the dictionary, counter(that word) and see if it is <= counter(input word). Once the program finds first anagram, it adds that word to candidate and proceeds to second loop to find the second word.

To put to simple words, if I input a word (or a phrase), I would like the program to run through a dictionary text file (which I have saved) and find two words from the dictionary that becomes anagram to my input. For instance, if I input "dormitory" the program output should be "dirty room" and if input "a gentleman", output "elegant man". Here is what I have done so far:

from pathlib import Path
from collections import Counter

my_dictionary = open(Path.home() / 'dictionary.txt')
my_words = my_dictionary.read().strip().split('\n')
my_dictionary.close()

letter_number = 0
my_word = []

print('Please type in your phrase:')
word = input()
word = word.replace(" ","")
word_map = Counter(word.lower())

for a_word in my_words:
    test = ''
    candidate = ''
    test_word = Counter(a_word.lower())
    for letter in test_word:
        if test_word[letter] <= word_map[letter]:
            test += letter
    if Counter(test) == test_word:
        candidate += a_word.lower()
        for a_word in my_words:
            test = ''
            test_word = Counter(a_word.lower())
            for letter in test_word:
                if test_word[letter] <= word_map[letter]:
                    test += letter
            if Counter(test) == test_word:
                candidate += a_word.lower()
            if Counter(candidate) == word_map:
                my_word.append(candidate)

print(my_word)

For some reason I am getting nothing from the output.

  1. I cannot get any result after I put my input.
  2. I also have tried to use del. command for getting rid of the word counter of first word from dictionary then proceed to find a second word from the dictionary but that didn't work either.

In summary, there must be some wrong place in the codes that flaws the program to not give any output.

Please help me figure out my mistake and error.

Thanks in advance.


Solution

  • Code can be optimized as follows:

    # script.py
    from pathlib import Path
    from collections import Counter
    
    filename = 'dictionary.txt'
    my_words = Path.home().joinpath(filename).read_text().strip().splitlines()
    
    word = input('Please type in your phrase:\n').replace(" ","")
    word_counter = Counter(word.lower())
    
    def parse(my_words=my_words):
        matches = []
        for a_word in my_words:       
            a_word_counter = Counter(a_word.lower())
            if all(c <= word_counter[w] for c in a_word_counter.values()):
                 matches.append(a_word)
        return matches
    
    def exactly_parse(my_words=my_words):
        return [w for w in my_words if Counter(w) == word_counter]
        
    my_word = parse()
    print(my_word)
    

    Let's say content of dictionary.txt:

    $ cat dictionary.txt
    how
    are
    you
    fine
    thanks
    
    • input word is how
    • What's the expected output? how
    $ python script.py
    Please type in your phrase:
    how
    ['how']
    
    $ python script.py
    Please type in your phrase:
    thanksyou
    ['you', 'thanks']