from __future__ import with_statement
import random
import os
with open('File1', 'r') as f1:
beginnings = [word.rstrip() for word in f1]
with open('File2', 'r') as f2:
endings = [word.rstrip() for word in f2]
with open('File3', 'w') as f3:
for beginning in beginnings:
f3.write('%s %s' % (beginning, random.choice(endings)))
f3.write(os.linesep)
import random
list1 = [ x.strip() for x in open('file1.txt', 'r').readlines()]
list2 = [ x.strip() for x in open('file2.txt', 'r').readlines()]
random.shuffle(list1)
random.shuffle(list2)
for word1, word2 in zip(list1, list2):
print word1, word2
from random import shuffle
words = []
for filename in ['File1', 'File2']:
with open(filename, 'r') as file:
# Opening the file using the with statement will ensure that it is properly
# closed when your done.
words.append((line.strip() for line in file.readlines()))
# The readlines method returns a list of the lines in the file
shuffle(words[-1])
# Shuffle will randomize them
# The -1 index refers to the last item (the one we just added)
从解析输入文件开始,这样就得到了一个包含两个列表的列表,每个列表都包含一个if文件中的单词。我们还将使用random模块中的shuffle方法将它们随机化:
接下来,我们必须将输出单词列表写入一个文件:
^{pr2}$相关问题 更多 >
编程相关推荐