2016-05-14 23 views
0

我正在處理某些事情。下面是該代碼需要做如何讀取文件,將內容放在數組中,將數組隨機混合,然後將混排數組寫入Python中的文件2.7

  1. 閱讀將每行成一個項目在一個陣列
  2. 文件
  3. 陣列洗牌成它可以作爲許多可能的洗牌。下面
  4. 將解釋創建一個新的文件來存儲洗牌的話

3號解釋: file.txt的包含以下

this 
is 
a 
test 

那就需要重新洗牌,以任何可能的結果。像這樣

this is a test 
this a is test 
this test is a 
this test a is 

依此類推等等。有16個可能的結果,所以我不會用它來解決我的問題。


我使用在Python 2.7

file = raw_input('Enter File Name: ') 
with open(file, 'r+') as f: 
    array = list(f) 
    print array 

以下代碼的輸出是這樣的,這是完全沒關係(除了 '\ N'):

['this\n', 'is\n', 'a\n', 'test'] 

現在,每當我使用shuffle()時,我正在使用此代碼

from random import shuffle 
file = raw_input('Enter File Name: ') 
with open(file, 'r+') as f: 
    array = list(f) 
    new = shuffle(array) 
    print new 

輸出是這樣的:

None 

我知道爲了寫,我需要使用W +和做f.write(新),然後f.close(),它會清除我的file.txt的,並將其保存空白

我該如何去做這件事?

+0

難道會有4! = 24種可能性而不是16種?無論如何 - 你是否熟悉'itertools'? –

+0

哦,是的。你是對的,我做了4 * 4而不是階乘。無論如何,我不是。我會看一看! – notissac

回答

0

您可以使用itertools

>>> import itertools 
>>> words = ['this', 'is', 'a', 'test'] 
>>> for p in itertools.permutations(words): print ' '.join(p) 

this is a test 
this is test a 
this a is test 
this a test is 
this test is a 
this test a is 
is this a test 
is this test a 
is a this test 
is a test this 
is test this a 
is test a this 
a this is test 
a this test is 
a is this test 
a is test this 
a test this is 
a test is this 
test this is a 
test this a is 
test is this a 
test is a this 
test a this is 
test a is this 

顯然,打印效果可以通過寫入一個文件被替換。

如果輸入文件不是太大,你可以替換內涵循環和使用整個文件的讀取和寫入:

import itertools 

with open('test.txt','r') as infile, open('shuffles.txt','w') as outfile: 
    words = infile.read().strip().split('\n') 
    shuffles = itertools.permutations(words) 
    output = '\n'.join(' '.join(shuffle) for shuffle in shuffles) 
    outfile.write(output) 
+0

這有助於很多,但我遇到了另一個問題。該文件應該已經打開了,不是嗎? http://prntscr.com/b41vh1 – notissac

+0

是的,在循環排列之前打開目標文件進行寫入。之後關閉它。 –