【问题标题】:How to take a string and return a list of all the words in a dictionary that differ from this word by exactly one letter?如何获取一个字符串并返回字典中与该单词相差一个字母的所有单词的列表?
【发布时间】: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


    【解决方案1】:

    我想你不应该重新发明轮子。有一个很好的 python library 实现了 Levenstein distance 指标。我想你会发现它很有用。

    【讨论】:

      【解决方案2】:

      让我们定义一个名为close_enough 的实用函数。它需要两个单词并返回True,如果单词的长度相同且仅相差一个字母:

      def close_enough(word1, word2):
          return len(word1) == len(word2) and 1 == sum(x!=y for x,y in zip(word1, word2))
      

      接下来,我们需要一个函数来搜索单词列表,名为wordlist,并选择close_enough(相差一个字母)的单词。这是一个功能。它需要两个参数:要比较的单词,称为mywordwordlist

      def one_letter_diff(myword, wordlist)
          return [word for word in wordlist if close_enough(word, myword)]
      

      如果您愿意,我们可以将 wordlist 设为全局:

      def one_letter_diff2(myword):
          # Uses global wordlist
          return [word for word in wordlist if close_enough(word, myword)]
      

      不过,一般来说,如果避免使用全局变量,程序逻辑会更容易理解。

      示例

      这里是close_enough 正在寻找哪些单词相差一个字母而哪些没有:

      In [22]: close_enough('hand', 'land')
      Out[22]: True
      
      In [23]: close_enough('hand', 'lend')
      Out[23]: False
      

      这是one_letter_diff 正在寻找wordlist 中与hand 相差一个字母的单词:

      In [26]: one_letter_diff('hand', ['land', 'melt', 'cat', 'hane'])
      Out[26]: ['land', 'hane']
      

      工作原理

      让我们先看看close_enough。如果满足两个条件,则返回 True。首先是单词的长度相同:

      len(word1) == len(word2) 
      

      第二个是它们只有一个字母的区别:

      1 == sum(x!=y for x,y in zip(word1, word2))
      

      让我们把它分解成几个部分。这会为每个不同的字母返回 True:

      [x!=y for x,y in zip(word1, word2)]
      

      例如:

      In [37]: [x!=y for x,y in zip('hand', 'land')]
      Out[37]: [True, False, False, False]
      

      sum 用于统计不同字母的个数。

      In [38]: sum(x!=y for x,y in zip('hand', 'land'))
      Out[38]: 1
      

      如果总和为一,则条件满足。

      one_letter_diff 中的命令是 _list comprehension`:

      [word for word in wordlist if close_enough(word, myword)]
      

      它遍历wordlist 中的每个单词并将其包含在最终列表中仅当 close_enough 返回 True。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-11
        相关资源
        最近更新 更多