gpt4 book ai didi

Python - 来自 2 个文件的行与\n

转载 作者:太空宇宙 更新时间:2023-11-04 07:56:15 25 4
gpt4 key购买 nike

我是 Python 新手。我有两个文件,其中包含我需要将 2 个文件逐行组合成一个文件的句子。

file_1.txt: 
feel my cold hands.
I love oranges.
Mexico has a large surplus of oil.
Ink stains don't rub out.

file_2.txt:
≥ª ¬˘ º’¿ª ¡ª ∏∏¡Æ∫¡.
∏«¸ ∫Ò«‡±‚∞° ∞≠¿ª ≥Øæ∆∞¨¥Ÿ.
∏flΩ√ƒ⁄ø°¥¬ ¥Ÿ∑Æ¿« ø©∫–¿« ºÆ¿Ø∞° ¿÷¥Ÿ.
¿◊≈© ¿⁄±π¿∫ ¥€æ∆µµ ¡ˆøˆ¡ˆ¡ˆ æ ¥¬¥Ÿ.



FINAL OUTPUT should look like:

feel my cold hands.
≥ª ¬˘ º’¿ª ¡ª ∏∏¡Æ∫¡.

I love oranges.
∏«¸ ∫Ò«‡±‚∞° ∞≠¿ª ≥Øæ∆∞¨¥Ÿ.

Mexico has a large surplus of oil.
∏flΩ√ƒ⁄ø°¥¬ ¥Ÿ∑Æ¿« ø©∫–¿« ºÆ¿Ø∞° ¿÷¥Ÿ.

Ink stains don't rub out.
¿◊≈© ¿⁄±π¿∫ ¥€æ∆µµ ¡ˆøˆ¡ˆ¡ˆ æ ¥¬¥Ÿ.

这是我尝试过的

filenames = ['data/data.txt', 'data/data2.txt']
with open('data/test.txt', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
for line in infile:
outfile.write(line)

这里的代码只是一个接一个地连接文件。但是,它不是逐行分割并创建\n。谢谢!!

引用资料: combine multiple text files into one text file using python

Python concatenate text files

最佳答案

所以诀窍是我们想同时遍历两个文件。为此,我们可以像这样使用 zip 函数:

filenames = ['data/data.txt', 'data/data2.txt']
with open('data/test.txt', 'w') as outfile:
with open(filenames[0]) as f1, open(filenames[1]) as f2:
for f1_line, f2_line in zip(f1, f2):
outfile.write(f1_line)
outfile.write(f2_line)
outfile.write("\n") # add blank line between each pair

关于Python - 来自 2 个文件的行与\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48328187/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com