蟒蛇新手,请耐心等待。我有两个文本文件,每个文本都有一个单词(一些有趣的单词)。我想创建一个随机组合的第三个文件。他们之间有空间。
示例:
File1:
Smile
Sad
Noob
Happy
...
File2:
Face
Apple
Orange
...
File3:
Smile Orange
Sad Apple
Noob Face
.....
我怎么能用Python?
谢谢!
答案 0 :(得分:2)
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)
答案 1 :(得分:1)
首先解析输入文件,最后得到两个列表的列表,每个列表包含文件中的单词。我们还将在随机模块中使用shuffle方法对它们进行随机化:
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.
答案 2 :(得分:1)
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
答案 3 :(得分:0)
尝试这样的事情:
file1 = []
for line in open("file1.txt"):
file1.append(line)
#or just list(open("file1.txt"))
...
file3 = open('file3.txt','w')
file3.write(...)
然后解决这个问题。查看random
模块及其功能。 (http://docs.python.org/library/random.html)
如果您不熟悉Python,请查看在线提供的潜入Python(http://diveintopython3.ep.io/)等教程。
答案 4 :(得分:0)
f = open(file,'r')
data = [" "]
while data[-1] != "":
data += [f.readline()
# do this a second time for the second file
然后
out = ""
from random import randint
for x in xrange(len(data)):
y = randint(0, len(data) -1)
if data[y] != 0:
out += data[y] + "\n"
data[y] = 0
f3 = open(third file,'w+b')
f3.write(out)
这是一个糟糕的代码,但它应该可行
答案 5 :(得分:0)
这是一个快速尝试...
import random f1 = [line.rstrip() for line in open('file1', 'r').readlines()] f2 = [line.rstrip() for line in open('file2', 'r').readlines()] random.shuffle(f1) random.shuffle(f2) out = zip(f1, f2) f3 = open('file3', 'w') for k, v in out: f3.write(k + ' ' + v + '\n')