2017-06-27 7 views
0

私は2つの入力ファイルを持っています次のようになります。並び替えるファイルおよびプリント偶数ライン

permuated-keywords.txt

one two three 
one three two 
two one three 
two three one 
three one two 
three two one 
four five 
five four 
six 

複数sentances.txtこのコードがエラーなしで実行されますが、中に行の正しい番号を入れていません

This is a sentance with keyword one two three. 
This is a sentance with keyword one two three. 
This is a sentance with keyword one two three. 
This is a sentance with keyword one two three. 
This is a sentance with keyword one two three. 
This is a sentance with keyword one two three. 
This is a sentance with keyword four five. 
This is a sentance with keyword four five. 
This is a sentence with keyword six. 

複数sentances.txt

from itertools import permutations 

import operator 
from collections import Counter 
from math import factorial 
def npermutations(l): 
    num = factorial(len(l)) 
    mults = Counter(l).values() 
    den = reduce(operator.mul, (factorial(v) for v in mults), 1) 
    return num/den 


with open('sentances.txt', 'r') as longfile: 
    with open('multiple-sentances.txt', 'w') as out2: 
     with open('keywords.txt', 'r') as shortfile: 
     with open('permuated-keywords.txt', 'w') as out: 
      for line in shortfile: 
       perm=('\n'.join(map(' '.join, permutations(line.split())))) 
       numofperms=npermutations(line.split()) 
       out.write(perm) 
       out.write('\n') 
       for line in longfile: 
        for i in range(numofperms): 
        out2.write(line) 

+1

あなたの意図した結果はまったく明らかではありません。 –

答えて

1

私は、次のコードがあなたを助けることを願っています。それはあまり「エレガント」ではないように見えますが、機能しています。

import itertools 
import os 

with open(os.path.join(os.getcwd(),'keywords.txt'), 'r') as keyfile: 
    keywords_list = keyfile.readlines() 
    keywords_perm = [] 
    new_file = [] 
    with open(os.path.join(os.getcwd(),'sentences.txt'), 'r') as sentences: 
     sentences_list = sentences.readlines() 
    with open(os.path.join(os.getcwd(),'multiple-sentances.txt'), 'w') as new: 
     i = 0 
     for key in keywords_list: 
      perm = itertools.permutations(key.split()) 
      for element in perm: 
       keywords_perm.append(element) 
       if sentences_list[i].find(" ".join(key.split())) != -1: 
        new.write(sentences_list[i][:sentences_list[i].find(" ".join(key.split()))] + " ".join(key.split()) + "\n") 
       else: 
        i += 1 
        new.write(sentences_list[i][:sentences_list[i].find(" ".join(key.split()))] + " ".join(key.split()) + "\n") 
    with open(os.path.join(os.getcwd(),'permutated-keywords.txt'), 'w') as out: 
     for i in range (0, len(keywords_perm)): 
      out.write(" ".join(keywords_perm[i]) + "\n") 
関連する問題