给定一个单词列表,用它们制作一个短语子集

时间:2010-09-10 15:12:26

标签: python list string

在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 个答案:

答案 0 :(得分:2)

我觉得这样的东西会起作用,虽然我目前无法访问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])

答案 1 :(得分:1)

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 :(得分:0)

这将起作用,似乎相当有效。

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