Python:从两个文件随机组合
我刚接触Python,请多多包涵。我有两个文本文件,每个文件里每行都有一个单词(有些是搞笑的单词)。我想创建一个第三个文件,里面是这些单词的随机组合,中间用空格隔开。
举个例子:
File1:
Smile
Sad
Noob
Happy
...
File2:
Face
Apple
Orange
...
File3:
Smile Orange
Sad Apple
Noob Face
.....
我该怎么用Python来实现这个呢?
谢谢!
6 个回答
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
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
在编程中,有时候我们需要处理一些数据,比如从一个地方获取数据,然后把它放到另一个地方。这就像把水从一个杯子倒到另一个杯子一样。
有些时候,我们会用到一些工具或者库来帮助我们完成这些任务。这些工具就像是厨房里的刀、锅、铲子,能让我们更方便地做饭。
在这个过程中,我们可能会遇到一些问题,比如数据格式不对、数据丢失等等。这就像在做饭时,发现没有盐或者锅坏了,得想办法解决。
总之,编程就像做饭,需要准备好材料,使用合适的工具,并且在遇到问题时及时调整,才能做出美味的“菜肴”。
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)