Skip to content

Instantly share code, notes, and snippets.

@matsu7874
Created April 16, 2017 01:02
Show Gist options
  • Save matsu7874/02fae79dd109b899299390c701b14001 to your computer and use it in GitHub Desktop.
Save matsu7874/02fae79dd109b899299390c701b14001 to your computer and use it in GitHub Desktop.
Markdownのヘッダーをリストに変換して目次にする
import sys
def header_to_list(s):
header_level = 0
for c in s:
if c == '#':
header_level += 1
else:
break
ret = []
if header_level > 0:
if header_level > 1:
ret.append(' ' * (header_level - 1))
ret.append('-')
ret.append(s[header_level:].strip('\n'))
return ''.join(ret)
def main():
fin = open(sys.argv[1], 'r', encoding='utf_8')
lines = fin.readlines()
fin.close()
print('\n'.join([x for x in [header_to_list(line) for line in lines] if x]))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment