简单的txt转html的python脚本

本文介绍了一款用于将纯文本文件转换成HTML格式的Python脚本,该脚本可以很好地保留原始文本的格式,并对关键字进行高亮显示,适用于Ubuntu及Windows系统。

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


最近在ubuntu linux下混,可惜CppBlog下的FreeTextBox用firefox一打开就假死,而TextBox又不支持文本转html(主要是没有加换行),于是就写了一个脚本.
在/usr/bin中新建一个快捷方式,名为txt2htm,然后在属性中设为可执行,就可以用了 用法如
txt2htm xxx.txt

为了方便起见,大家可以新建一个后缀为txt的文件,点右键,选打开方式,输入命令txt2htm,然后确定,以后只要点点鼠标选"以...打开"就可以完成工作了.

windows下当然也可以使用这个脚本,添加到右键的方法是按着shift点右键,选打开方式.
--------------------------------------------------------------

#!/usr/local/bin/python
# -*-coding:UTF-8-*-

#txt2htm.py
#Author: 张沈鹏 zsp007@gmail.com
#Update: 2006-11-10 Beta0.2

import sys
import re

def htmlWrapper(content,tag,attr):
    return "<"+tag+" "+attr+">"+content+""

def fontColorWrapper(content,color):
    return htmlWrapper(content,'font','color="#'+color+'"')

def htmHighLight(line):
        keywords=["if","then","else","def","for","in","return","import","print","unsigned","long","int",\
        "short","include","class","void","while","const","template"
        ]
        
        for i in keywords:
                keywordMatcher=re.compile(r'\b'+i+r'\b')
                line = keywordMatcher.sub(fontColorWrapper(i,'cf0000'), line)

                
        return line
    

def txt2htm(txtName):
    txt=open(txtName)
    
    htmlName=filename+".html"
    htm=open(htmlName,"w")
    
    for line in txt:
        line=line\
            .replace('&','&')\
            .replace('<','<')\
            .replace('® ','® ')\
            .replace('"','"')\
            .replace('©','©')\
            .replace('™','™')\
            .replace('<','<')\
            .replace('\t',"    ").\
            replace(' ',' ')

        line="
"+htmHighLight(line)

        print line

        htm.write( line)
        
    txt.close()
    htm.close()

    
    print "\n转换成功,保存在"+htmlName+'\n'


if len(sys.argv) < 2:
    print "\n请指定要转换为htm的文件\n"
else:
    filename=sys.argv[1]
    txt2htm(filename)
 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值