2012-11-06 5 views
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() 
+1

확실히 그렇지 확인하기 위해 코드를 들여 끝내 g-거리다. 다른 사람이 코드 들여 쓰기를 수정하기 위해 편집을 넣었으나 이전에 가지고 있던 것과 일치하는지 다시 확인하십시오. – apnorton

+0

불량/바람직하지 않은 출력의 예는 무엇입니까? – Marius

+0

우리는'Wordlist.txt.txt'의 내용을 알지 못하고 출력물을 원하는 내용도 없기 때문에 여러분을 도울 수 없습니다. 자세한 정보를 제공해주십시오. – pydsigner

답변

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)) 
1

당신의 INFILE의 각 줄은 정확히 두 단어가 포함 된 경우 고려할 수 : 향후 참조를 위해

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])))