Python:两个文件的随机组合

2024-06-28 20:10:54 发布

您现在位置:Python中文网/ 问答频道 /正文

Python新手,请耐心听我说。我有两个文本文件,每一个都有一个单词(一些有趣的单词)。我想创建一个第三个文件,它有这些随机组合。他们之间有一个空间。在

示例:

File1:
Smile
Sad
Noob
Happy
...

File2:
Face
Apple
Orange
...

File3:
Smile Orange
Sad Apple
Noob Face
.....

我怎么能用Python编写这个呢?在

谢谢!在


Tags: 文件示例apple空间单词file1file2face
3条回答
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

从解析输入文件开始,这样就得到了一个包含两个列表的列表,每个列表都包含一个if文件中的单词。我们还将使用random模块中的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)

接下来,我们必须将输出单词列表写入一个文件:

^{pr2}$

相关问题 更多 >