Python项目一:即时标记

本文介绍了使用Python 3.4.3在Windows 7环境下实现的一个即时标记工具,该工具能够将纯文本转换为HTML,支持Markdown类似的功能,如标题、段落、列表、超链接和斜体等。通过读取test_input.txt文件并输出到test_output.html,展示了代码的运行方式及转换效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

分析python基础教程(第二版) 中的项目1
Python果然是少量代码就可以实现很多功能.
本项目是一个简易的标记添加器,为纯文本添加标签格式,使其能够在html中正确显示,就类似于markdown编辑器.

Python版本:3.4.3

操作系统:win7

代码地址:https://code.youkuaiyun.com/ranky2009/pythonsmallproject

实例:

纯文本如下(test_input.txt):

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 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.

From this page you my visit several of our interesting web pages:

    -what is SPAM? (http://wwspam.fu/whatisspam)
    
    -How do they make it? (http://wwspam.fu/howtomakeit)
    
    
you can get in touch with us in *many* ways

经过转换后如下(test_output.html):
 

<html><head><title>...</title></head><body>
<h1>
A short history of the company
</h1>
<p>
World Wide Spam was started in the summer of 2000. The business 
concept was to ride the dot-com wave and make money both through
bulk email and by selling canned meat online.
</p>
<p>
After receiving several complaints from customers who weren't 
satisfied by their bulk email.
</p>
<p>
From this page you my visit several of our interesting web pages:
</p>
<ul>
<li>
what is SPAM? (<a href="http://wwspam.fu/whatisspam">http://wwspam.fu/whatisspam</a>)
</li>
<li>
How do they make it? (<a href="http://wwspam.fu/howtomakeit">http://wwspam.fu/howtomakeit</a>)
</li>
</ul>
<p>
you can get in touch with us in <em>many</em> ways
</p>
</body></html>


根据以上对比发现,即时标记器作了如下修改:
1. 将单行转化为h1的标题
2. 将多行转化为段落p
3. 将带有“-”的行转化为列表
4. 将链接文本转化为html中的超链接
5. 将*号之间的字符转换为斜体
6. 去掉了多余的换行

 

代码(test.py):

import sys, re

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 = []

class Handler:
    def callback(self, prefix, name, *args):
        method = getattr(self, prefix+name, None)
        if callable(method): return method(*args)
    d
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值