python - 在 Python 中使用字典查找字谜

标签 python

我正在尝试在 python 中创建一个函数,该函数将使用字典打印出文本文件中单词的字谜。我已经查看了数百个类似的问题,所以如果这是重复的,我很抱歉,但我似乎找不到适合我的问题的解决方案。

我明白我需要做什么(至少我是这么认为),但我陷入了最后一部分。

这是我到目前为止所拥有的:

with open('words.txt', 'r') as fp:
    line = fp.readlines()

def make_anagram_dict(line):
    dict = {}
    for word in line:
        key = ''.join(sorted(word.lower()))
        if key in dict.keys():
            dict[key].append(word.lower())
        else:
            dict[key] = []
            dict[key].append(word.lower())
    if line == key:
        print(line)


make_anagram_dict(line)

我认为我需要一些东西来将每个值的键与其他值的键进行比较,然后在它们匹配时进行打印,但我无法让某些东西起作用。

目前,我能做的最好的事情就是打印出文件中的所有键和值,但理想情况下,我能够打印文件中的所有字谜。

输出:我没有具体指定的输出,但有以下内容: [猫:行动,tac]

对于每个字谜。 再次,如果这是重复,我们深表歉意,但我们将不胜感激任何帮助。

最佳答案

我不确定输出格式。在我的实现中,所有字谜词最后都会打印出来。

with open('words.txt', 'r') as fp:
    line = fp.readlines()

def make_anagram_dict(line):
    d = {}  # avoid using 'dict' as variable name

    for word in line:
        word = word.lower()  # call lower() only once
        key = ''.join(sorted(word))
        if key in d:  # no need to call keys()
            d[key].append(word)
        else:
            d[key] = [word]  # you can initialize list with the initial value

    return d  # just return the mapping to process it later

if __name__ == '__main__':
    d = make_anagram_dict(line)

    for words in d.values():
        if len(words) > 1:  # several anagrams in this group
            print('Anagrams: {}'.format(', '.join(words)))

此外,请考虑使用 defaultdict - 它是一个字典,可为新键创建指定类型的值。

from collections import defaultdict

with open('words.txt', 'r') as fp:
    line = fp.readlines()

def make_anagram_dict(line):
    d = defaultdict(list)  # argument is the default constructor for value

    for word in line:
        word = word.lower()  # call lower() only once
        key = ''.join(sorted(word))
        d[key].append(word)  # now d[key] is always list

    return d  # just return the mapping to process it later

if __name__ == '__main__':
    d = make_anagram_dict(line)

    for words in d.values():
        if len(words) > 1:  # several anagrams in this group
            print('Anagrams: {}'.format(', '.join(words)))

关于python - 在 Python 中使用字典查找字谜,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54623084/

相关文章:

python - 按类别内的标题过滤(多对多)

Python Pandas 获取不包括当前行的累积和(cumsum)

python - 为什么线程的参数有时会在 Python 中混淆?

python - 编写了我的第一个 Python 程序,感谢用户输入递增

python - 根据 Python 中的字符串列表交叉检查文件行

python - 检查 gdb pretty-print 中的内存

python - Numbapro 停止在 GPU 上工作

python - 具有复合键的 Flask-SQLAlchemy 多对多

python - 从python中的列表列表构造共现矩阵

python - 如何在 .yaml 文件环境变量中声明值并在 Jenkins 中调用它