我正在尝试制作一个扰乱句子顺序的程序。程序必须获取输入文件并将其加密为输出文件。但是,当句子被扰乱时,应根据其原始顺序对它们进行编号。例如,
输入
I love apples
I love candy
I love God
输出
2:I love candy
3:I love God
1:I love apples
我真的不确定如何开始,所以如果你能提供想法或方法来解决这个问题,或者我应该使用哪些功能和方法,那将是非常好的。
答案 0 :(得分: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)
答案 1 :(得分: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))
答案 2 :(得分: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)
答案 3 :(得分: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))