Python Forum
Highlighting Python Code in HTML.
Thread Rating:
  • 2 Vote(s) - 2.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Highlighting Python Code in HTML.
#1
I don't know if python has a module. That already can do this.
Little script that highlight python code.
It a copy n paste html to static webpage.
TODO triple quotes.

Is there a way to get all keywords. Like open and len ?
Is there anything I forgot ?

import keyword
import sys
import re

class HighlightPyInHtml:
    def __init__(self):
        self.system_args()
        self.at = '<em class="at">@{0}</em>'
        self.span = '<span class="{0}">{1}</span>'
        self.common = '<em class="common">{0}</em>'
        self.keywords = keyword.kwlist + ['open', 'len']
        self.string_type = None
        for arg in self.args:
            self.encode(arg)

    def system_args(self):
        self.args = []
        for arg in sys.argv[1:]:
            if arg.endswith('.py'):
                self.args.append(arg)

    def tag_string(self, html, word):
        if self.tag is None:
            self.tag = self.tag_string
            self.string_type = word
            html.write('<span class="string">' + word)
        elif word == self.string_type:
            self.tag = None
            html.write(word + '</span>')
        else:
            html.write(word)

    def tag_dot(self, html, word):
        if self.tag is None:
            self.tag = self.tag_dot
        else:
            self.tag = None

        html.write(word)

    def tag_def(self, html, word):
        if word != ' ':
            self.tag = None
            html.write(self.span.format('def', word))
        else:
            html.write(word)

    def tag_comment(self, html, word):
        if self.tag is None:
            self.tag = self.tag_comment
            html.write('<span class="comment">#')
        elif word == '\n':
            self.tag = None
            html.write('</span>\n')
        else:
            html.write(word)

    def tag_class(self, html, word):
        if word != ' ':
            self.tag = None
            html.write(self.span.format('classname', word))
        else:
            html.write(word)

    def tag_at(self, html, word):
        if self.tag is None:
            self.tag = self.tag_at
        else:
            self.tag = None
            html.write(self.at.format(word))

    def tag_number(self, html, word):
        if self.tag is None:
            self.tag = self.tag_number
            html.write('<span class="number">' + word)
        elif word == '.':
            self.tag = self.tag_number_dot
        else:
            self.tag = None
            html.write('</span>')
            self.encode_tag(html, word)

    def tag_number_dot(self, html, word):
        self.tag = None
        if word.isdigit():
            html.write('.{0}</span>'.format(word))
        else:
            html.write('.')
            self.encode_tag(html, word)

    def encode(self, pyfile):
        self.tag = None
        with open(pyfile[:-2] + 'html', 'w') as html:
            html.write('<!doctype html>\n<html>\n<head>\n')
            html.write('    <link rel="stylesheet" href="code.css">\n')
            html.write('</head>\n<body>\n<pre><code>')
            with open(pyfile, 'r') as program:
                for line in program:
                    line = re.split('(\W)', line)
                    line = [l for l in line if l != '']

                    for word in line:
                        self.encode_tag(html, word)

            html.write('</code></pre>\n</body>\n</html>\n')

    def encode_tag(self, html, word):
        if self.tag:
            self.tag(html, word)
        elif word in ['"', "'"]:
            self.tag_string(html, word)
        elif word == '.':
            self.tag_dot(html, word)
        elif word == '@':
            self.tag_at(html, word)
        elif word == "#":
            self.tag_comment(html, word)
        elif word in self.keywords:
            if word == "class":
                self.tag = self.tag_class
            elif word == "def":
                self.tag = self.tag_def

            html.write(self.span.format("keyword", word))
        elif word.isdigit():
            self.tag_number(html, word)
        elif word in ['self', 'cls']:
            html.write(self.common.format(word))
        else:
            html.write(word)

HighlightPyInHtml()
code.css
99 percent of computer problems exists between chair and keyboard.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020