拆分由特殊ch分隔的文本文件

2024-10-01 07:41:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件test.txt,其中包含以下数据:

content content
more content
content conclusion
==========
content again
more of it
content conclusion
==========
content
content
contend done
==========

我想得到一个由==========分隔的块列表。在

对于上面的例子,我希望是这样的:

^{pr2}$

另外,如果有人能分享一个执行此操作的一般过程(如果有的话),我将不胜感激。在

灵感来自:Splitting large text file on every blank line


Tags: of数据testtxt列表moreitcontent
3条回答
y="""content content
more content
content conclusion
==========
content again
more of it
content conclusion
==========
content
content
contend done
=========="""
x=re.compile(r"(?:^|(?<=={10}))\n*([\s\S]+?)\n*(?=={10}|$)")
print re.findall(x, y)

输出:

['content content\nmore content\ncontent conclusion', 'content again\nmore of it\ncontent conclusion', 'content\ncontent\ncontend done']

可以使用正则表达式基于3个或更多=字符拆分文件。然后用反斜杠替换新行:

import re

with open(file_name) as f:
    my_list = [chunk.strip().replace('\n', '\\') for chunk in re.split(r'={3,}', f.read())]

如果您知道等号的确切长度,则可以使用字符串拆分方法:

^{2}$

另外请注意,反斜杠用于转义字符,如果在字符串中使用反斜杠,它将转义下一个字符,这意味着如果您的特殊字符不会被解释为其原始含义。在

因此,最好用另一个分隔符分隔行:

N = 5 # this is an example
with open(file_name) as f:
    my_list = [chunk.strip().strip().replace('\n', '/') for chunk in f.read().split('=' * N)]

使用split方法。在

with open('file.txt') as f:
    data = f.read()
print(data.split('=========='))

相关问题 更多 >