[英]Split the text file in python
我有一个文本文件,其中包含一些具有类似字段的记录。
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:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.