Adam Rochlen
Adam Rochlen

Reputation: 21

improving a word combination script

Any way to make this better or more simple? I know it generates a whole lot of words and when you try to combine more than 4 lines on one sentence it doesn't look the way it should.

infile = open('Wordlist.txt.txt','r')
wordlist = []
for line in infile:
    wordlist.append(line.strip())
infile.close()
outfile = open('output.txt','w')
for word1 in wordlist:
    for word2 in wordlist:
        out = '%s %s' %(word1,word2)
        #feel free to #comment one of these two lines to not output to file or screen
        print out
        outfile.write(out + '\n')

outfile.close()

Upvotes: 2

Views: 130

Answers (2)

Don Question
Don Question

Reputation: 11614

If each line in your infile contains exactly 2 words you may consider:

from itertools import product

with open('Wordlist.txt.txt','r') as infile:
   wordlist=infile.readlines()

with open('output','w') as ofile:
   ofile.write('\n'.join(map(product, [line.strip().split() for line in wordlist])))

Upvotes: 1

inspectorG4dget
inspectorG4dget

Reputation: 114025

Use itertools.product

with open('Wordlist.txt.txt') as infile:
    words = [line.strip() for line in infile]

with open('output.txt', 'w') as outfile:
    for word1, word2 in itertools.product(words, repeat=2):
        outfile.write("%s %s\n" %(word1, word2))

Upvotes: 4

Related Questions