【问题标题】:How can I read a file, put contents in an array, shuffle the array, and then write the shuffled array to the file in python 2.7如何读取文件,将内容放入数组中,随机播放数组,然后将随机播放的数组写入 python 2.7 中的文件
【发布时间】:2016-09-10 20:57:34
【问题描述】:

我正在做某事。这是代码需要做的事情

  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(new) 然后 f.close(),它会清除我的 file.txt 并将其保存为空白

我该怎么做?

【问题讨论】:

  • 不会有 4 个吧! = 24 种可能性而不是 16 种?无论如何——你熟悉itertools吗?
  • 哦,是的。你是对的,我做了 4*4 而不是阶乘。反正我不是。我去看看!

标签: arrays python-2.7 file


【解决方案1】:

你可以使用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)

【讨论】:

  • 这很有帮助,但我遇到了另一个问题。该文件应该已经打开了,不是吗? prntscr.com/b41vh1
  • 是的,在遍历排列之前打开目标文件进行写入。之后关闭它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-31
  • 1970-01-01
  • 1970-01-01
  • 2011-01-27
相关资源
最近更新 更多