A little while ago I was trying to port my blogs from Blogger.com to code4reference.com. But when I tried to port the blog, I noticed that the code section of my blog contained <br/> HTML tags for new line. When I used the the Syntaxhighlighter, the view was awful since the Syntax highter expects the code as written on text edittor without any <br/>.  The Syntax highlighter treats  <br/> tag as a string rather than as a new line. Now there was huge task to remove the unwanted <br/> tag from my code sections. Well I started thinking how to make this task easier. No wonder, I thought of writing a small python script substituting <br/> with ‘\n’. This script is improvised and doesn’t cater to professional needs. However, one can learn to open file, parse the string,  substitute values, and create time temp file from this example code.

#!/usr/bin/env python
from tempfile import mkstemp
from shutil import move
from os import remove, close
import sys

def replace(filename, pattern, subst):
    #Create temp file
    fh, abs_path = mkstemp()
    new_file = open(abs_path,'w')
    old_file = open(filename)
    for line in old_file:
        new_file.write(line.replace(pattern, subst))
    #close temp file
    new_file.close()
    close(fh)
    old_file.close()
    #Remove original file
    remove(filename)
    #Move new file
    move(abs_path, filename)

def main():
    if len(sys.argv) != 2:
        print ('%(prog)s filename ')
        exit()

    replace(sys.argv[1],"<br />",'\n')

if __name__=="__main__":
    """If the this file  run as program then execute the main method"""
    main()

, ,
Trackback

no comment untill now

Add your comment now