我有一串这样的文本:
'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'
我需要将这个字符串拆分成一个字符串列表,这些字符串被拆分成这些 block :
['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”,但不包括该元素中的下一个)。我该怎么做?
编辑:假设除了上面的文本字符串之外,我还有其他如下所示的文本字符串:
'closeloop start
closeloop ..up:677 down:098
closeloop start
closeloop ..up:568 down:123'
我的代码遍历每个文本字符串并使用拆分代码将其拆分为列表。但是当它到达这串文本时,它找不到任何要拆分的内容——所以我如何包含一个命令来拆分“closeloop start”行(如果它们出现)和 tx 行(如果它们出现)?我试过这段代码,但出现类型错误:
data = re.split(r'\n((?=tx)|(?=closeloop\sstart))', data)
最佳答案
您可以拆分后跟 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']
但是,如果您只是循环遍历输入文件对象(逐行读取),您可以在收集行时处理每个 block :
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)
关于python - 根据关键字python拆分文本字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45967621/