python给文本添加html标记

基础教程有个转换实例,将文本文件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):


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值