簡體   English   中英

Python:兩個文件的隨機組合

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM