[英]Python: Random combination from two files
蟒蛇新手,忍受我。 我有两个文本文件,每个文本都有一个单词(一些有趣的单词)。 我想创建一个随机组合的第三个文件。 他们之间有空间。
例:
File1:
Smile
Sad
Noob
Happy
...
File2:
Face
Apple
Orange
...
File3:
Smile Orange
Sad Apple
Noob Face
.....
我怎么能用Python呢?
谢谢!
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)
首先解析输入文件,最后得到两个列表的列表,每个列表包含文件中的单词。 我们还将在随机模块中使用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.
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
尝试这样的事情:
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,请查看在线提供的Dive into Python( http://diveintopython3.ep.io/ )等教程。
你可以做点什么
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)
这是一个可怕的代码,但它应该工作
这是一个快速尝试......
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.