基础教程有个转换实例,将文本文件test_input.txt转换为浏览器可打开的文件test_output.html。代码如下:
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 = []
主程序simple_markup.py:
#!/usr/bin/env python
import sys,re
from util import *
print '<html><head><title>...</title><body>'
title = True
for block in blocks(sys.stdin):
block = re.sub(r'\*(.+?)\*',r'<em>\1</em>',block)
if title:
print '<h1>'
print block
print '</h1>'
title = False
else:
print '<p>'
print block
print '</p>'
print '</body></html>'
测试文本文件test_input.txt:
My favorite class
My favorite class
It is not easy to choose a favorite class. However, while I find many of my courses interesting, *my favorite class* is spoken English class. The reason why I like the class are various.
First, unlike other class, spoken English class is free to talk. In the class, we can talk any topic, it is no need to sit silently, the aim of the class is to speak, students are encouraged to give their ideas freely. The students and the teacher give reaction to each other, we will not be sleepy easily.
Second, as the class is much free to talk, students won't feel embarrassed when they are making mistakes. When we are having other class, we need to answer the teachers' questions, if we give the wrong answer, we will feel dismay, but in the spoken English class is different, the more we say, the better, because practice means perfect, no one will laugh at the mistake.
I like spoken English class, every time when I have the class, I feel easy and happy to learn. I don't have pressure to make mistakes, because all of us will do, only practice makes perfect.
执行:python simple_markup.py < test_input.txt > test_output.html
结果(浏览器打开test_output.html):