首页 > 解决方案 > 如何将 3 个 txt 文件组合在一起

问题描述

我制作了 3 个文本文件,其中包含 1 或 2 个句子。

我知道如何在 txt 文件中读取行并将它们完全结合起来。

我不知道如何组合所有的句子。

ex) 如果句子是 A,B,C

结果可能是 ABC 或 ACB 或 CBA 或 BCA ...

我有 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()

这些是我的代码,如果您有任何想法,请帮助我!

标签: pythonpython-3.xfile

解决方案


我不知道您为什么要排列这些行以选择 6 个随机行。我认为排列是指洗牌。10 行的排列将为您提供 3628800 行组合。所以我给出了一个解决方案,从 10 行中随机选择 6 行并将其写入文件。

输出a1.txt:

  1. 这是文件 1
  2. 这是富
  3. 这是文件1的结尾

输出a2.txt

  1. 这是文件 2
  2. 这是酒吧
  3. 这是文件2的结尾

输出a3.tx

  1. 这是文件 3
  2. 这是巴兹
  3. 这是文件3的结尾
  4. 就这样

现在这三个文件组合起来将有 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()

推荐阅读