我正在编写一个Python程序,它可以对给定的输入字符串进行解读,对解读后的字符串进行排列并检查字典中的常用单词

问题描述 投票:0回答:1

我尝试使用 set 找到我的解读排列字典和字典单词字典之间的交集,但它返回了

unhashable type: list error

我该如何解决它以及我做错了什么?

from collections import defaultdict
from itertools import permutations


class possibleWords:
    
    """
    Python program to find all possible dictionary words from a scrambled input word.
    """
    
    def __init__(self, scrambled_word):
        self.scrambled_word=scrambled_word
        self.length=len(scrambled_word)
        self.unscramble_dict=defaultdict(list)
        self.words_dict=defaultdict(list)
        
    def unscramble(self):
        """
        this method takes the scrambled word and finds all permutations from that scrambled word.
        in every iteration the permutation object Returns a list with items of the same character length. it then adds the list as the value to a dictionary with the key being the length of the items.
        """
        
    
        for r in range(2,self.length+1):
            permutation_object=permutations(self.scrambled_word, r)
            unscrambled_list=[''.join(permutation) for permutation in permutation_object]
            self.unscramble_dict[r].append(unscrambled_list)
        return self.unscramble_dict


    def english_words(self):
        """
        this method Returns a dictionary with same key as of unscramble and a value as a list with the key length
        """
        self.length=len(self.scrambled_word)
        words_list=[]
        
        with open("english_words.txt") as file_object:
            for line in file_object:
                word=line.strip()
                for r in range(2,self.length+1):
                    if len(word)==r:
                        self.words_dict[len(word)].append(word)
        return self.words_dict



instance1= possibleWords("sodwind")


def main():
"""
this function Returns A list with the common list value of the same key between unscramble and English words
"""
    unscramble_dict=instance1.unscramble()
    words_dict=instance1.english_words()
    common_word= {k: list(set(v).intersection(unscramble_dict[k])) for k, v in words_dict.items()}
    return common_word
    
print(main())

python set permutation intersection scramble
1个回答
0
投票

我不确定这是否是您正在寻找的,但此功能通过将打乱的单词与按字母顺序排序的单词进行匹配来解读它

from english_words import get_english_words_set

words = get_english_words_set(['web2'], lower=True)

def unscramble(word:str) -> str:
    output = []
    for i in words:
        if sorted(i.lower()) == sorted(word.lower()):
            output.append(i)
    return ', '.join(output)
© www.soinside.com 2019 - 2024. All rights reserved.