简体   繁体   English

如何将3个txt文件合并在一起

[英]How could I combine 3 txt file together

I've made 3 text files with 1 or 2 sentences inside. 我制作了3个文本文件,其中包含1或2个句子。

I know how to readlines inside txt file and combine them altogether. 我知道如何在txt文件中读取行并将其完全合并。

I have no idea how to combine all the sentences. 我不知道如何组合所有句子。

ex) If sentences are A,B,C 例如)如果句子是A,B,C

Results might be ABC or ACB or CBA or BCA ... 结果可能是ABC或ACB或CBA或BCA ...

I have 10 sentence and wanna combine 6 of them randomly. 我有10个句子,想随机组合其中6个。

def output() :          
     infile=open("file.txt","r")
     outfile=open("outputone.txt","w")

     line= open('outputa1.txt').readlines()
     line=''.join(line)
     outfile.write("\n")

def output1() :

     line= open('outputa2.txt').readlines()
     line=''.join(line)
     outfile.write(line)
     outfile.write("\n")

def output2() :

     line= open('outputa3.txt').readlines()
     line=''.join(line)
     outfile.write(line)
     outfile.write("\n")

     infile.close()
     outfile.close()

output()
output1()
output2()

These are my code if you have any ideas please help me !! 这些是我的代码,如果您有任何想法请帮助我!

I don't know why you want to permute the lines for selecting 6 random lines. 我不知道您为什么要为选择6条随机线而排列这些线。 I think by permutation you mean shuffling. 我认为排列是指改组。 Permutation of 10 lines will give you 3628800 combinations of the lines. 10行的排列会给您3628800行的组合。 So I am giving a solution to randomly select 6 lines from 10 lines and write it into a file. 因此,我提供了一种从10行中随机选择6行并将其写入文件的解决方案。

outputa1.txt: outputa1.txt:

  1. This is file 1 这是文件1
  2. This is foo 这是foo
  3. This is the end of file 1 这是文件1的结尾

outputa2.txt outputa2.txt

  1. This is file 2 这是文件2
  2. This is bar 这是酒吧
  3. This is the end of file 2 这是文件2的结尾

outputa3.tx outputa3.tx

  1. This is file 3 这是文件3
  2. This is baz 这是巴兹
  3. This is the end of file 3 文件3到此结束
  4. That's all 就这样

Now these three files combined will have 10 lines. 现在,这三个文件合起来将有10行。

import random
combined_lines = []
f = open('outputa1.txt','r')
for line in f:
    combined_lines.append(line+'\n')
f.close()
f = open('outputa2.txt','r')
for line in f:
    combined_lines.append(line+'\n')
f.close()
f = open('outputa3.txt','r')
for line in f:
    combined_lines.append(line+'\n')
f.close()
#To choose randomly 6 lines from the file
random.shuffle(combined_lines)
f = open('outputa.txt','x')
f.writelines(combined_lines[:6])
f.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM