Skip to content

Instantly share code, notes, and snippets.

@gabriel-tincu
Last active August 29, 2015 14:23
Show Gist options
  • Save gabriel-tincu/1ce8b5e0a506d2cebe96 to your computer and use it in GitHub Desktop.
Save gabriel-tincu/1ce8b5e0a506d2cebe96 to your computer and use it in GitHub Desktop.
def split_header_footer(filetext, header_re, footer_re):
import re
import os
text = filetext
header_start = None
for h in header_re:
s = h.search(text)
if s is not None:
header_start = s.start()
break
if header_start is None:
print('Header not found')
header = []
header_start = 0
else:
header_start = text.rfind(os.linesep, 0, header_start)
header = text[:header_start].split(os.linesep)
footer_start = None
for f in footer_re:
s = f.search(text[header_start:])
if s is not None:
footer_start = s.start()
break
if footer_start is None:
print('Footer not found')
body = text[header_start:].split(os.linesep)
else:
footer_start = text.rfind(os.linesep, 0, footer_start)
body = text[header_start:footer_start].split(os.linesep)
footer = text[footer_start:].split(os.linesep) if footer_start is not None else []
all_lines = []
for content, repl in [(header, 'HEADER'), (body, 'CONTENT'), (footer, 'FOOTER')]:
content = [x.replace('LINE', repl) for x in content]
all_lines.extend(content)
return os.linesep.join(all_lines)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment