截断特定字符前后的文本 python
Truncating texts before and after a certain character python
我正在阅读 python、
中的大量文本
文本格式为:
blablabla
***** END HEADER ******
valid content
***** start footer *****
blablalba
我需要删除所有文本中的页眉和页脚,方法是删除所有字符串,直到 ***** END HEADER ***** 和 ***** start footer ***** 之后的所有内容
如有任何帮助,我们将不胜感激
到目前为止我试过这个:
import re
chop = re.compile('(/.+)*** END HEADER *****', re.DOTALL)
data_chopped = chop.sub('', text_file)
但我一直收到错误消息:
sre_constants.error: multiple repeat at position
可能还有其他有效的方法,一种方法可能是尝试使用多个拆分:
txt = """blablabla
***** END HEADER ******
valid content
***** start footer *****
blablalba
"""
# split the header and take the second section of split
tmp = ''.join(txt.split('***** END HEADER ******')[1])
# split by footer and take the first section of split
tmp2 = ''.join(tmp.split('***** start footer *****')[0])
result = tmp2.strip()
print(result)
结果:
'valid content'
我正在阅读 python、
中的大量文本文本格式为:
blablabla
***** END HEADER ******
valid content
***** start footer *****
blablalba
我需要删除所有文本中的页眉和页脚,方法是删除所有字符串,直到 ***** END HEADER ***** 和 ***** start footer ***** 之后的所有内容
如有任何帮助,我们将不胜感激
到目前为止我试过这个:
import re
chop = re.compile('(/.+)*** END HEADER *****', re.DOTALL)
data_chopped = chop.sub('', text_file)
但我一直收到错误消息:
sre_constants.error: multiple repeat at position
可能还有其他有效的方法,一种方法可能是尝试使用多个拆分:
txt = """blablabla
***** END HEADER ******
valid content
***** start footer *****
blablalba
"""
# split the header and take the second section of split
tmp = ''.join(txt.split('***** END HEADER ******')[1])
# split by footer and take the first section of split
tmp2 = ''.join(tmp.split('***** start footer *****')[0])
result = tmp2.strip()
print(result)
结果:
'valid content'