Python's Instant tagging project practice notes _python

Source: Internet
Author: User
Tags in python

This is the practice behind the Python Basics tutorial, which is written to familiarize yourself with Python's code, and practise practice with basic and rudimentary syntax in Python.

The project was simple at first, but after refactoring it was a bit more complicated, but more flexible.

According to the book, after refactoring the program, divided into four modules: Handler module, filter module, rules (in fact, should be processing rules), parser.

First, the handler module, which has two functions, one is to provide the output of those fixed HTML tags (each with start and end), and the other is to provide a friendly interface for beginning and ending the markup output. Look at the program handlers.py:

Copy Code code as follows:

Class Handler:
'''
'''
Def callback (self, prefix, name, *args):
method = GetAttr (Self,prefix+name,none)
If callable (method): Return method (*args)
def start (self, name):
Self.callback (' Start_ ', name)
Def end (self, name):
Self.callback (' End_ ', name)
def sub (self, name):
def substitution (match):
result = Self.callback (' sub_ ', name, match)
If result is None:match.group (0)
return result
return substitution

Class Htmlrenderer (Handler):
'''

'''
def start_document (self):
print ' def end_document (self):
print ' </body>def start_paragraph (self):
print ' <p> '
def end_paragraph (self):
print ' </p> '
def start_heading (self):
print ' def end_heading (self):
print ' def start_list (self):
print ' <ul> '
def end_list (self):
print ' </ul> '
def start_listitem (self):
print ' <li> '
def end_listitem (self):
print ' </li> '
def start_title (self):
print ' def end_title (self):
print ' def sub_emphasis (self, Match):
Return ' <em>%s</em> '% match.group (1)
def sub_url (self, Match):
Return ' <a href= '%s ' >%s</a> '% (Match.group (1), Match.group (1))
def sub_mail (self, Match):
Return ' <a href= ' mailto:%s ' >%s</a> ' (Match.group (1), Match.group (1))
Def feed (self, data):
Print data

This program is the cornerstone of the entire project: the output of the label, and the replacement of the string. It is also easier to understand.

The second module, "Filter", is simpler, but it is a string of regular expressions. The relevant code is as follows:

Copy Code code as follows:

Self.addfilter (R ' \* (. +?) \* ', ' emphasis ')
Self.addfilter (R ' (http://[\.a-z0-9a-z/]+) ', ' url ')
Self.addfilter (R ' ([\.a-za-z]+@[\.a-za-z]+[a-za-z]+) ', ' Mail ')

This is the three filters, respectively: Emphasis brand filter (with x marked), URL card filter, email card filter. Students who are familiar with regular expressions have no pressure to understand.

Let's look at the third module, "Rules," This module, aside from that grandparent class, the two methods that other classes should have are condition and action, the former being used to determine whether the read strings conform to their own rules, and the latter is used to perform operations, and the so-called execution is to invoke the handler module , before the output label, the content, the post label. Take a look at the code of this module, in fact, the relationship between several classes, drawing into the class diagram will be more clear. rules.py:

Copy Code code as follows:

Class rule:
def action (self, block, handler):
Handler.start (Self.type)
Handler.feed (Block)
Handler.end (Self.type)
Return True

Class headingrule (rule):
Type = ' Heading '
def condition (self, Block):
return not ' \ n ' in block and Len (blocks) <= and not block[-1] = = ': '

Class Titlerule (Headingrule):
Type = ' title '
i = True

def condition (self, Block):
If not Self.first:return False
Self.first = False
Return Headingrule.condition (self, block)

Class listitemrule (rule):
Type = ' ListItem '
def condition (self, Block):
return block[0] = = '-'
def action (Self,block,handler):
Handler.start (Self.type)
Handler.feed (Block[1:].strip ())
Handler.end (Self.type)
Return True

Class Listrule (listitemrule):
    type = ' list '
    inside = False
 & nbsp;  def condition (self, block):
        return True
     DEF action (Self,block, handler):
        if not self.inside and Listitemrule.condition (self,block):
            Handler.start (self.type)
            self.inside = True
        elif Self.inside and not Listitemrule.condition (Self,block):
            handler.end (self.type)
             self.inside = False
         Return False

Class paragraphrule (rule):
Type = ' paragraph '
def condition (self, Block):
Return True

Supplementary utils.py:

Copy Code code as follows:

def line (file):
For line on File:yield line
Yield ' \ n '

def blocks (file):
block = []
For line in lines (file):
If Line.strip ():
Block.append (line)
Elif BLOCK:
Yield '. Join (block). Strip ()
block = []

Finally, a grand look at the "parser module," The role of this module is to coordinate the reading of the text and other modules of the relationship. To focus on that, it provides two lists of "rules" and "filters," and the advantage of this is that the flexibility of the entire program is greatly improved, making the rules and filters into hot-swappable ways, Of course, this is also due to the previous rules and filters in the writing of each type of rule (filter) is written in a separate class, not with the IF. else to differentiate. Look at the code:

Copy Code code as follows:

Import SYS, RE
From handlers Import *
From util import *
From rules Import *

Class Parser:
def __init__ (Self,handler):
Self.handler = Handler
Self.rules = []
Self.filters = []

def addrule (self, rule):
Self.rules.append (rule)

def addfilter (self,pattern,name):
DEF filter (block, handler):
return re.sub (Pattern, handler.sub (name), block)
Self.filters.append (Filter)

Def parse (self, file):
Self.handler.start (' document ')
For blocks in blocks (file):
For filter in Self.filters:
Block = Filter (block, Self.handler)
For the rule in Self.rules:
If Rule.condition (block):
last = rule.action (blocks, Self.handler)
If Last:break
Self.handler.end (' document ')

Class Basictextparser (Parser):
def __init__ (Self,handler):
parser.__init__ (Self,handler)
Self.addrule (Listrule ())
Self.addrule (Listitemrule ())
Self.addrule (Titlerule ())
Self.addrule (Headingrule ())
Self.addrule (Paragraphrule ())

Self.addfilter (R ' \* (. +?) \* ', ' emphasis ')
Self.addfilter (R ' (http://[\.a-z0-9a-z/]+) ', ' url ')
Self.addfilter (R ' ([\.a-za-z]+@[\.a-za-z]+[a-za-z]+) ', ' Mail ')

Handler = Htmlrenderer ()
Parser = Basictextparser (handler)

Parser.parse (Sys.stdin)

In this module, the idea is to traverse the client (that is, the entrance to the program execution) to all the rules and filters that are inserted to process the read text.

There is a detail of the place to say, in fact, and the previous written echoes, that is, when traversing the rules by calling condition this thing to determine whether the current rules.

I think this program is very similar to the command line mode, you can review the pattern, to maintain the memory network node of the solid.

And finally, what I thought was the purpose of this program:

1, used to do code highlighting analysis, if rewritten into a JS version, you can do an online code editor.
2, can be used for learning, for me to write blog.

There are other ideas that can leave your insights.
Adding a class diagram is simple, but it should explain the relationship. In addition, I suggest that if you look at the code to smooth the relationship is best to draw their own drawings to be familiar with the entire structure.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.