python新手,请耐心听我说。我有两个文本文件,每个文件一行都有一个单词(一些有趣的单词)。我想创建第三个文件,其中包含这些文件的随机组合。它们之间有一个空格。
示例:
File1:
Smile
Sad
Noob
Happy
...
File2:
Face
Apple
Orange
...
File3:
Smile Orange
Sad Apple
Noob Face
.....我怎么才能使用Python呢?
谢谢!
发布于 2010-11-10 11:01:31
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)发布于 2010-11-10 11:00:32
首先解析输入文件,最后得到一个包含两个列表的列表,每个列表包含一个if文件中的单词。我们还将在random模块中使用随机方法对它们进行随机化:
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)接下来,我们必须将输出单词列表写入一个文件:
with open('File3', 'w') as out_file:
for pair in zip(words):
# The zip method will take one element from each list and pair them up
out_file.write(" ".join(pair) + "\n")
# The join method will take the pair of words and return them as a string,
# separated by a space.发布于 2010-11-10 11:10:15
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, word2https://stackoverflow.com/questions/4140798
复制相似问题