2

有什么办法可以使这更好或更简单?我知道它会生成很多单词,当您尝试在一个句子中组合超过 4 行时,它看起来并不像它应该的那样。

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()
4

2 回答 2

4

利用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))
于 2012-11-06T02:21:05.393 回答
1

如果您的 infile 中的每一行恰好包含 2 个单词,您可以考虑:

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])))
于 2012-11-06T02:26:40.957 回答