python - 如何将 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()
这些是我的代码,如果您有任何想法,请帮助我!
解决方案
我不知道您为什么要排列这些行以选择 6 个随机行。我认为排列是指洗牌。10 行的排列将为您提供 3628800 行组合。所以我给出了一个解决方案,从 10 行中随机选择 6 行并将其写入文件。
输出a1.txt:
- 这是文件 1
- 这是富
- 这是文件1的结尾
输出a2.txt
- 这是文件 2
- 这是酒吧
- 这是文件2的结尾
输出a3.tx
- 这是文件 3
- 这是巴兹
- 这是文件3的结尾
- 就这样
现在这三个文件组合起来将有 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()
推荐阅读
- php - Grav/twig:想要制作自定义 yaml 对象并在自定义页面部分中检索它们的数据
- c# - Net Core 3.0:具有整数变量的多个复选框
- python - Tkinter 实心边框按钮
- python - python中的合并排序:切片与迭代-对复杂性的影响
- javascript - 如何使用日期更改输入元素的值?val()/attr()/change() 不工作
- c# - C# 复制字典
- javascript - 如何在 JavaScript Postman Runner 中比较两个 URL
- excel - 循环引用,即使代码不应该那样创建它
- dialogflow-es - Google Action Basic Card 响应锁定在 Google Nest Hub 上
- r - 从linkcomm包中检索二进制交互作为R中的数据框