分析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