DigitalMag

md => html table generation

Jan 14th, 2021
416
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import re
  2.  
  3. tag_in = lambda x, v: f'<{x}>{v}</{x}>'
  4.  
  5. def replace(matchobj):
  6.     blocks = matchobj.groupdict()
  7.     md_header = blocks['header']
  8.     md_lines = blocks['lines']
  9.  
  10.     header = ''.join(tag_in('th', v) for v in md_header.split('|') if v)
  11.     lines = ''
  12.     for line in md_lines.strip().split('\n'):
  13.         lines += tag_in('tr', ''.join(tag_in('td', v) for v in line.split('|')))
  14.     return tag_in('table', tag_in('tr', header) + tag_in('tbody', lines))
  15.  
  16. def main():
  17.  
  18.     with open('md.table.txt', 'r', encoding="utf-8") as eyes:
  19.         text = eyes.read()
  20.     reg = r'\|{0,1}(?P<header>([ \w\d\-|_]+\|)+[ \w\d\-|_]+\|{0,1})(\r\n|\r|\n)' + \
  21.         r'\|{0,1}((:){0,1}\--*(:){0,1}\|)+(:){0,1}\--*(:){0,1}\|{0,1}(\r\n|\r|\n)' + \
  22.         r'(?P<lines>(\|{0,1}([ \w\d\-|_]+\|{0,1})+(\r\n|\r|\n))*)'
  23.     r = re.search(reg, text)
  24.     s = re.sub(reg, replace, text)
  25.     print(s)
  26.  
  27. if __name__ == '__main__':
  28.     main()
RAW Paste Data