首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python:来自两个文件的随机组合

Python:来自两个文件的随机组合
EN

Stack Overflow用户
提问于 2010-11-10 10:50:32
回答 5查看 1K关注 0票数 1

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

示例:

代码语言:javascript
运行
复制
File1:
Smile
Sad
Noob
Happy
...

File2:
Face
Apple
Orange
...

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

我怎么才能使用Python呢?

谢谢!

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2010-11-10 11:01:31

代码语言:javascript
运行
复制
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)
票数 2
EN

Stack Overflow用户

发布于 2010-11-10 11:00:32

首先解析输入文件,最后得到一个包含两个列表的列表,每个列表包含一个if文件中的单词。我们还将在random模块中使用随机方法对它们进行随机化:

代码语言:javascript
运行
复制
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)

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

代码语言:javascript
运行
复制
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.
票数 1
EN

Stack Overflow用户

发布于 2010-11-10 11:10:15

代码语言:javascript
运行
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4140798

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档