如何从关键字列表中生成所有组合?

时间:2016-01-13 17:00:53

标签: python combinations

我想创建域名生成器,我列出了像这样的关键字>

with

我想为每一行创建所有可能的组合,我怎样才能在Python中做到这一点?

我需要这样的输出:

mare italia offerte agosto 2013
mare italia 2013 offerte
mare italia villaggi
mare italia last second
mare italia vacanze
mare italia last minute 2012
mare italia offerte agosto 2012
mare italia offerte last minute
mare italia bello
mare italia piu bello
mare italia hotel
mare italia residence

我的启动python代码是:

mare italia
mare italia offerte 
mare italia offerte agosto
mare italia offerte agosto 2013
italia offerte agosto 2013
offerte agosto 2013
agosto 2013
2013 agosto
offerte 2013
2013 offerte
offerte italia
... more

2 个答案:

答案 0 :(得分:0)

您可以使用itertools.combinations

from itertools import combinations

seen = set()  # keep track of printed lines

with open("keywords.txt") as f:
    for line in f:
        words = line.rstrip().split()

        for i in range(2, len(words)):
            for c in combinations(words, i):
                l = " ".join(c)
                if l not in seen:
                    print(l) 
                    seen.add(l)

答案 1 :(得分:0)

这将打印所有不同的行

from itertools import combinations


final=set()

with open('keywords.txt') as file:
    for line in file:
        words=line.strip().split()
        for i in range(2,len(words)):
            for j in combinations(words,i):
                final.add(' '.join(j))

print '\n'.join(final)