置换文件并从第二个文件打印偶数行

时间:2017-06-27 05:55:16

标签: python python-3.x permutation itertools multiple-files

我有两个输入文件:

sentances.txt

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

keywords.txt

one two three
four five
six

我希望输出文件看起来像:

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.

此代码运行时没有错误,但没有在multiple-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 个答案:

答案 0 :(得分:1)

我希望,以下代码可以帮助您。它似乎不那么“优雅”,但它正在发挥作用。

{{1}}