【发布时间】:2015-01-21 12:21:09
【问题描述】:
所以现在我正在处理一本很长的 A-Z 单词词典。使用这本字典,我正在尝试创建一个函数,该函数将字符串作为参数并返回该字典中在任何时候都有一个字母不同的所有单词。例如。
>>> oneLetterDiff('find')
['bind', 'kind', 'lind', 'mind', 'rind', 'wind', 'fend', 'fond', 'fund', 'fine', 'fink', 'finn', 'fins']
>>> words=oneLetterDiff('hand')
>>> print words
['band', 'land', 'rand', 'sand', 'wand', 'hard', 'hang', 'hank', 'hans']
>>> oneLetterDiff('horse')
['morse', 'norse', 'worse', 'house', 'horde', 'horst']
>>> oneLetterDiff('monkey')
['donkey']
>>> oneLetterDiff('action')
[]
我已经导入了一个单独的函数,该函数在我调用 WordLookup 时运行良好。它看起来像这样:
def createDictionary():
"""
Creates a global dict of all the words in the word file.
Every word from the word list file because a key in the dict.
Each word maps to the value None. This is because all we care about
is whether a given word is in the dict.
"""
global wordList # Specifies that wordList will not go away at the end
# of this function call and that other functions may
# use it
wordList = dict()
wordFile = open('WordList.txt')
for word in wordFile:
word = word.strip() # remove leading or trailing spaces
# map the word to an arbitrary value that doesn't take much
# space; we'll just be asking "in" questions of the dict
wordList[word] = None
wordFile.close()
def lookup(word):
global wordList # states that the function is using this global variable
return word in wordList
按照这段代码,我得到了实际的 oneLetterDiff 函数:
def oneLetterDiff(myString):
theAlphabet = string.ascii_lowercase
for i in myString:
for j in theAlphabet:
#Maybe try to see if the letters can be changed in this fashion?
有人能帮我更好地理解这一点吗?我一直在努力寻找合适的解决方案,感谢您提供任何帮助!
【问题讨论】:
标签: python search dictionary