【发布时间】:2019-12-12 03:51:39
【问题描述】:
您好,我有一个下面的文件数据,我希望对其进行处理以获得预期的输出,只是想知道作为 python 学习者是否有办法基于启动和停止布尔索引来实现这一点。
这里的文件行总是以名为 SRV: 的字符串开头,尽管在某些情况下这些行在同一行开始和结束,而在某些情况下这些行会扩展为换行符。
文件文本数据:
SRV: this is for bryan
SRV: this is for terry
SRV: this is for torain
sec01: This is reserved
sec02: This is open for all
sec03: Closed!
SRV: this is for Jun
预期输出:
SRV: this is for bryan
SRV: this is for terry
SRV: this is for torain sec01: This is reserved sec02: This is open for all sec03: Closed!
SRV: this is for Jun
有没有一种 Pythonic 方式可以更好地实现这一点,我也可以使用 pandas。
【问题讨论】:
-
您可以尝试使用类似
df[0].groupby(df[0].str.startswith('SRV').cumsum()).apply(' '.join)的内容,其中0是列名。 (注意:这是使用熊猫数据框) -
@anky_91,这也可以。
标签: regex linux python-3.x pandas