根据关键字python拆分文本字符串

时间:2017-08-30 18:38:43

标签: python string list split

我有一串这样的文字:

'tx cycle up.... down
rx cycle up.... down
phase:...
rx on scan: 123456
tx cycle up.... down
rx cycle up.... down
phase:...
rx on scan: 789012
setup
tx cycle up.... down
rx cycle up.... down
tx cycle up.... down
rx cycle up.... down'

我需要将此字符串拆分为分成这些块的字符串列表:

['tx cycle up.... down rx cycle up.... down phase:.... rx on scan: 123456', 
 'tx cycle up.... down rx cycle up.... down phase:.... rx on scan: 789012',
 'tx cycle up... down rx cycle up.... down',
 'tx cycle up... down rx cycle up.... down']

有时他们有一个'阶段'和'扫描'号码,但有时他们没有,我需要这个足够通用,适用于任何这些情况,并且必须对大量数据执行此操作。

基本上,我想将其拆分为一个字符串列表,其中每个元素从'tx'的出现延伸到下一个'tx'(包括第一个'tx',但不包括该元素中的下一个'tx')。我怎么能这样做?

编辑:假设除了上面的文字字符串,我还有其他文字字符串,如下所示:

'closeloop start
closeloop ..up:677 down:098
closeloop start
closeloop ..up:568 down:123'

我的代码遍历每个文本字符串,并使用拆分代码将其拆分为列表。但是当它到达这个文本字符串时,它将找不到任何要拆分的东西 - 那么如果它们出现的话,如何在'closeloop start'行中包含一个命令来拆分,如果出现这些行,那么tx行就像之前一样?我尝试了这段代码,但我得到了一个TypeError:

data = re.split(r'\n((?=tx)|(?=closeloop\sstart))', data)

1 个答案:

答案 0 :(得分:7)

您可以拆分后跟tx的新行:

import re

re.split(r'\n(?=tx)', inputtext)

演示:

>>> import re
>>> inputtext = '''tx cycle up.... down
... rx cycle up.... down
... phase:...
... rx on scan: 123456
... tx cycle up.... down
... rx cycle up.... down
... phase:...
... rx on scan: 789012
... setup
... tx cycle up.... down
... rx cycle up.... down
... tx cycle up.... down
... rx cycle up.... down'''
>>> re.split(r'\n(?=tx)', inputtext)
['tx cycle up.... down\nrx cycle up.... down\nphase:...\nrx on scan: 123456', 'tx cycle up.... down\nrx cycle up.... down\nphase:...\nrx on scan: 789012\nsetup', 'tx cycle up.... down\nrx cycle up.... down', 'tx cycle up.... down\nrx cycle up.... down']
>>> from pprint import pprint
>>> pprint(_)
['tx cycle up.... down\nrx cycle up.... down\nphase:...\nrx on scan: 123456',
 'tx cycle up.... down\nrx cycle up.... down\nphase:...\nrx on scan: 789012\nsetup',
 'tx cycle up.... down\nrx cycle up.... down',
 'tx cycle up.... down\nrx cycle up.... down']

但是,如果您只是循环输入文件对象(逐行读取),则可以在收集行时处理每个块:

section = []
for line in open_file_object:
    if line.startswith('tx'):
        # new section
        if section:
            process_section(section)
        section = [line]
    else:
        section.append(line)
if section:
    process_section(section)

如果您需要匹配多个起始行,请在每个起始行中包含| - 分开的替代方案:

data = re.split(r'\n(?=tx|closeloop\sstart)', data)