Python 有关从字典中查找 Anagram 的问题

Python Question Relating to Finding Anagram from Dictionary

我正在努力完成这个项目。

编辑:我希望程序从字典中找到 2 个单词,它们是输入单词的变位词。我想处理这个程序的方法是使用 counter(input()),然后循环遍历字典内容两次(找到第一个字词变位词,然后找到下一个字词)。该循环将从字典中取出每个单词,counter(that word) 并查看它是否 <= counter(input word)。一旦程序找到第一个变位词,它就会将该词添加到候选词中,然后进入第二个循环以找到第二个词。

简单来说,如果我输入一个词(或短语),我希望程序 运行 通过字典文本文件(我已保存)并从中找到两个词根据我的输入变成字谜的字典。例如,如果我输入“宿舍”,程序输出应该是“脏房间”,如果输入“绅士”,输出“优雅的男人”。这是我到目前为止所做的:

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)

出于某种原因,我没有从输出中得到任何信息。

  1. 输入后无法得到任何结果。
  2. 我也试过用del。命令从字典中删除第一个单词的单词计数器,然后继续从字典中查找第二个单词,但这也不起作用。

综上所述,一定是代码中有错误的地方导致程序没有输出。

请帮我找出我的错误和错误。

提前致谢。

代码可以优化如下:

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

假设dictionary.txt的内容:

$ cat dictionary.txt
how
are
you
fine
thanks
  • 输入的单词是how
  • 预期的输出是什么?怎么样
$ python script.py
Please type in your phrase:
how
['how']

$ python script.py
Please type in your phrase:
thanksyou
['you', 'thanks']