gpt4 book ai didi

python - 在python中分割文本文件

转载 作者:行者123 更新时间:2023-11-30 23:39:22 25 4
gpt4 key购买 nike

我有一个文本文件,其中一些记录具有类似的字段。

    name:
Class:
Subject:
name:
Class:
Subject:

如上所述,该文件可以有任意数量的记录,我想用各自的字段分隔每个记录。以下是我为了解决这个问题可以达到的程度。

    def counter(file_path):
count = 0
file_to_read = open(file_path)
text_to_read = file_to_read.readlines()
file_to_read.close()
for line in text_to_read:
if line.find('name') != -1:
count = count + 1
return count

这样我就可以数数了。文件中存在的记录数,现在我发现很难将整个文本文件分割为等于 no 的段。记录。

提前致谢

最佳答案

def records(file_path):
with open(file_path) as f:
chunk = []
for line in f:
if 'name' in line:
if chunk:
yield chunk
chunk = [line]
else:
chunk.append(line)
if chunk:
yield chunk

for record in records('data.txt'):
print '--------'
print ''.join(record)

打印

--------
    name:
    Class:
    Subject:

--------
    name:
    Class:
    Subject:

关于python - 在python中分割文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13622326/

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