如何读取文件,将内容放入数组,随机播放数组,然后将混洗数组写入python 2.7中的文件

时间:2016-05-14 19:01:51

标签: arrays python-2.7 file

我正在做点什么。这是代码需要做的事情

  1. 阅读文件
  2. 将每一行放入数组中的项目
  3. 将阵列随机播放到尽可能多的shuffle中。将在下面解释
  4. 创建一个新文件来存储随机字样
  5. 第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并将其保存为空白

    我该怎么做呢?

1 个答案:

答案 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)