简单的txt转html的python脚本


最近在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: 张沈鹏 [email protected]
#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)
 

你可能感兴趣的:(Python)