gpt4 book ai didi

python - 如何将文本文件拆分成 block ?

转载 作者:行者123 更新时间:2023-12-05 09:28:25 25 4
gpt4 key购买 nike

我尝试了很多方法,但都没有用。我想将文本文件行拆分为多个 block 。具体来说,每个 block 50 行。

像这样 [['Line1', 'Line2' -- 最多 50] 等等。

最佳答案

data.txt(示例):

Line2
Line2
Line3
Line4
Line5
Line6
Line7
Line8

Python代码:

with open('data.txt', 'r') as file:
sample = file.readlines()

chunks = []
for i in range(0, len(sample), 3): # replace 3 with 50 in your case
chunks.append(sample[i:i+3]) # replace 3 with 50 in your case

chunks(在我的示例中,3 行的 block ):

[['Line1\n', 'Line2\n', 'Line3\n'], ['Line4\n', 'Line5\n', 'Line6\n'], ['Line7\n', 'Line8']]

您可以在这些行上应用 string.rstrip('\n') 方法以删除末尾的 \n

替代方案:
不读取内存中的整个文件(更好):

chunks = []

with open('data.txt', 'r') as file:
while True:
chunk = []
for i in range(3): # replace 3 with 50 in your case
line = file.readline()
if not line:
break
chunk.append(line)
# or 'chunk.append(line.rstrip('\n')) to remove the '\n' at the ends
if not chunk:
break
chunks.append(chunk)

print(chunks)

产生相同的结果

关于python - 如何将文本文件拆分成 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71330427/

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