我正在尝试创建一个列表字典,其中的关键字是anagrams,并且值(列表)包含所有可能出现的字符。从myFile中删除 n
所以我的字典应该包含这样的
{'aaelnprt': ['parental', 'paternal', 'prenatal'], ailrv': ['rival']}
可能的话是一个.txt文件中。每个单词用换行符分隔的地方。示例
Sad
Dad
Fruit
Pizza
这导致了一个问题,当我尝试编码它。
with open ("word_list.txt") as myFile:
for word in myFile:
if word[0] == "v": ##Interested in only word starting with "v"
word_sorted = ''.join(sorted(word)) ##Get the anagram
for keys in list(dictonary.keys()):
if keys == word_sorted: ##Heres the problem, it doesn't get inside here as theres extra characters in <word_sorted> possible "\n" due to the linebreak of myfi
print(word_sorted)
dictonary[word_sorted].append(word)
问:如果word_sorted有换行符,不应该只保留在字典的键值中。对不起,如果这是一个noob问题,但为什么要换行是特殊的? – Brad 2014-10-17 07:13:02