Search code examples
pythonpermutationpython-itertoolswords

How do I see if a value matches another value in a text file in Python?


Here's what I have so far.

from itertools import permutations

original = str(input('What word would you like to unscramble?: '))

for bob in permutations(original):
    print(''.join(bob))



inputFile = open(dic.txt, 'r')
compare = inputFile.read()
inputFile.close()

Basically, what I'm trying to do is create a word unscrambler by having Python find all possible rearrangements of a string and then only print the rearrangements that are actual words, which can be found out by running each rearrangement through a dictionary file (in this case dic.txt) to see if there is a match. I am running Python 3.3, if that matters. What do I need to add in order to compare the rearrangements with the dictionary file?


Solution

  • You could store the permutations in a list, add the dictionary in another list and select those being in both lists…

    For example this way:

    from itertools import permutations
    
    original = str(input('What word would you like to unscramble?: '))
    
    perms = []
    for bob in permutations(original):
        perms.append(''.join(bob))
    
    
    
    inputFile = open(dic.txt, 'r')
    dict_entries = inputFile.read().split('\n')
    inputFile.close()
    
    for word in [perm for perm in perms if perm in dict_entries]:
        print word
    

    (Assuming the dictionary contains one word per line…)