我正在尝试在 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/