2

これをより良く、またはよりシンプルにする方法はありますか? 大量の単語が生成されることはわかっていますが、1 つの文に 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 に答える