代码之家  ›  专栏  ›  技术社区  ›  JiminyCricket

给出一个单词列表,用它们组成短语的子集

  •  1
  • JiminyCricket  · 技术社区  · 14 年前

    在python中获取单词列表并将它们转换为短语的最佳方法是什么。

    words = ["hey","there","stack","overflow"]
    print magicFunction(words)
    >>> ["hey","there","stack","overflow", "hey there stack","hey there", "there stack overflow","there stack", "stack overflow", "hey there stack overflow" ]
    

    更新:应该是更具体的,单词必须是连续的,如在我的例子打印出来的列表。所以我们可以说“你好”,但不能说“你好”

    3 回复  |  直到 14 年前
        1
  •  1
  •   Jon-Eric    14 年前
    import itertools
    
    # Adapted from Python Cookbook 2nd Ed. 19.7.
    def windows(iterable, length=2, overlap=0):
        """
        Return an iterator over overlapping windows of length <length> of <iterable>.
        """
        it = iter(iterable)
        results = list(itertools.islice(it, length))
        while len(results) == length:
            yield results
            results = results[length-overlap:]
            results.extend(itertools.islice(it, length-overlap))
    
    def magic_function(seq):
        return [' '.join(window) for n in range(len(words)) for window in windows(seq, n + 1, n)]
    

    >>> words = ["hey","there","stack","overflow"]
    >>> print magic_function(words)
    ['hey', 'there', 'stack', 'overflow', 'hey there', 'there stack', 'stack overflow', 'hey there stack', 'there stack overflow', 'hey there stack overflow']
    
        2
  •  2
  •   recursive    14 年前

    我认为这样的方法会奏效,尽管我目前还没有python的访问权限。

    def magic_function(words):
      for start in range(len(words)):
        for end in range(start + 1, len(words) + 1):
          yield " ".join(words[start:end])
    
        3
  •  0
  •   Charles Ma    14 年前

    def magicFunction(words):
        phrases = []
        start = 0
        end = 0
        for i in xrange(1, len(words) + 1):
            start = 0
            end = i
            while (end <= len(words)):
                phrases.append(" ".join(words[start:end]))
                start += 1
                end += 1
        return phrases