【问题标题】:Splitting text file delimited by special character [duplicate]拆分由特殊字符分隔的文本文件[重复]
【发布时间】:2017-05-18 13:24:31
【问题描述】:

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

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

我想获得由========== 分隔的块列表。

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

foo = ["content content\more content\content conclusion",
       "content again\more of it\content conclusion",
       "content\content\contend done"]

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

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

【问题讨论】:

  • 你试过了吗?
  • open(...).read().split('==========')
  • 尝试删除所有[\r]\ns 并在分隔符处拆分。

标签: python string file python-3.x


【解决方案1】:
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']

【讨论】:

  • 这行得通!感谢您的时间和精力。
  • 为什么投反对票?
【解决方案2】:

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

import re

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

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

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

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

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

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)]

【讨论】:

  • 我得到了不同的输出:my_list = ['content content\\more content\\content conclusion\\', '', '\\content again\\more of it\\content conclusion\\', '', '\\content\\content\\contend done\\', '', '\\']
  • @KshitijSaraogi 查看更新。
  • 我仍然需要优化输出。 my_list=['content content/more content/content conclusion', '', 'asdasd #92012 blaablaa 30 70/content again/more of it/content conclusion', '', 'asdasd #299 yadayada 60 40/content/content/contend done', '', '']
猜你喜欢
  • 2014-10-03
  • 2011-09-08
  • 2014-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-20
  • 1970-01-01
相关资源
最近更新 更多