#-*- coding: utf-8 -*
__author__ = ‘geebos‘
importreimportmarkdownfrom pygments importhighlightfrom pygments.token importText, STANDARD_TYPESfrom pygments.formatter importFormatterfrom pygments.lexers importget_lexer_by_namefrom pygments.lexers importguess_lexerdef_get_ttype_class(ttype):
fname=STANDARD_TYPES.get(ttype)iffname:returnfname
aname= ‘‘
while fname isNone:
aname= ‘-‘ + ttype[-1] +aname
ttype=ttype.parent
fname=STANDARD_TYPES.get(ttype)return fname +anamedef_line_num_tag_gen():
line_num=0defresult():
nonlocal line_num
line_num+= 1
return f‘
returnresultclassHtmlLiFormatter(Formatter):def __init__(self, **options):
Formatter.__init__(self, **options)def_get_css_class(self, ttype):"""Return the css class of this token type prefixed with
the classprefix option."""ttypeclass=_get_ttype_class(ttype)ifttypeclass:returnttypeclassreturn ‘‘
defhtml_encode(self, value):if ‘
value= value.replace(‘‘ invalue:
value= value.replace(‘>‘, ‘>‘)returnvaluedef_get_css_classes(self, ttype):"""Return the css classes of this token type prefixed with
the classprefix option."""cls=self._get_css_class(ttype)while ttype not inSTANDARD_TYPES:
ttype=ttype.parent
cls= self._get_css_class(ttype) + ‘ ‘ +clsreturnclsdefformat(self, tokensource, outfile):
get_line_num_tag=_line_num_tag_gen()
line_start_tag= ‘
‘line_end_tag= ‘‘code_tags= [‘- ‘]
num_tags= [‘
- ‘]
line_value= ‘‘outfile.write(‘
temp_tokensource =[]for ttype, value intokensource:
value= value.replace(‘ ‘, ‘ ‘)if ttype == Text and ‘\n‘ invalue:
values= re.findall(pattern=‘([^\n]*)(\n)([^\n]*)‘, string=value)for i invalues:for k ini:if k != ‘‘:
temp_tokensource.append((ttype, k))else:
temp_tokensource.append((ttype, value))for ttype, value intemp_tokensource:
ttype_class=self._get_css_classes(ttype)
value=self.html_encode(value)if value != ‘\n‘:
line_value+= f‘{value}‘
else:
num_tags.append(get_line_num_tag())
code_tags.append(f‘{line_start_tag}
line_value= ‘‘num_tags.append(‘‘)
code_tags.append(‘‘)
outfile.write(f‘{"".join(num_tags)}{"".join(code_tags)}‘)
outfile.write(‘
type_and_content= re.findall(pattern=‘```(\w*)[\n|\r]([^`]+)```‘, string=match.group(0))
formatter= HtmlLiFormatter(linenos=True, style=‘colorful‘)
code_type=type_and_content[0][0]
code_content= type_and_content[0][1]if code_type != ‘‘:
substring= highlight(code=code_content, lexer=get_lexer_by_name(code_type), formatter=formatter)else:
substring= highlight(code=code_content, lexer=guess_lexer(code_content), formatter=formatter)returnsubstringdefmd_to_html(mdstr):
sub_string= re.sub(pattern=‘```([^`]+)```‘, repl=code_to_html, string=mdstr)
exts= [‘markdown.extensions.extra‘, ‘markdown.extensions.tables‘]
html= markdown.markdown(sub_string, extensions=exts)returnhtmlif __name__ == ‘__main__‘:#在这里调用md_to_html就可以将md文件内容转化为str类型的html代码
res = md_to_html(open(‘blog.md‘, ‘r‘, encoding=‘utf8‘).read())
htmlstr= ‘
‘ + res + ‘‘open(‘webpage.html‘, ‘w‘, encoding=‘utf8‘).write(htmlstr)