我正在做点什么。这是代码需要做的事情
第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(new)然后f.close(),它清除我的file.txt并将其保存为空白
我该怎么做呢?
答案 0 :(得分: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)