0

我正在尝试制作一个打乱句子顺序的程序。程序必须获取输入文件并将其打乱到输出文件中。但在打乱句子时,应按原顺序编号。例如,

输入

I love apples  
I love candy  
I love God

输出

2:I love candy

3:I love God

1:I love apples

我真的不知道如何开始,所以如果你能给我提供解决这个问题的想法或方法,或者我应该使用什么功能和方法,那就太好了。

4

4 回答 4

1

假设你有一个数组sentences

#zip in the original order
sentences = zip(range(len(sentences)), sentences)    
random.shuffle(sentences)
for i, sentence in sentences:
   print "{0}: {1}".format(i, sentence)
于 2013-11-09T02:46:14.940 回答
0

您似乎对其他答案有疑问,所以这是一个完整的解决方案,我已经测试过它应该可以工作:

from random import shuffle

finput = 'path/input.txt'
foutput = 'path/output.txt'

with open(finput, 'r') as fin, open(foutput, 'w') as fout:
    sentences = fin.readlines()

    #add the order using enumeration
    sentences = list(enumerate(sentences))
    shuffle(sentences)
    for i, sentence in sentences:
        fout.write("{0}: {1}".format(i + 1, sentence))  
于 2013-11-09T04:55:26.787 回答
0
from random import shuffle

def scramble(infile, outfile):
    with open(infile) as f1, open(outfile, 'w') as f2:
        myrows = list(enumerate(f1, 1))
        shuffle(myrows)
        f2.writelines(('%-4d: %s' % r for r in myrows))

scramble(__file__, '/tmp/scrambled.txt')
with open('/tmp/scrambled.txt') as sf:
    print ''.join(sf)
于 2013-11-09T02:52:24.863 回答
0
import random
with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
  suffixes = []
  for i,line in enumerate(infile):
    line = line.strip()
    prefix, suffix = line.rsplit(' ', 1)
    suffixes.append((i,suffix))

  random.shuffle(suffixes)
  for i,suffix in suffixes:
    print("%d:%s %s" %(i, prefix, suffix))
于 2013-11-09T02:28:34.143 回答