Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

C++ Style Comment Stripper (See related posts)

// This scirpt either removes the C++ style comments or places them
// just before the line in which they occur
// for ex:
//
// int i=0, sum; //This is some comment(embedded)
//
// after conversion:
// //This is some comment(embedded)
// int i=0, sum;

# comm_stripper
#
# Description :
#
#   This scirpt either removes the C++ style comments or places them
#   just before the line in which they occur
#   for ex:
#
#       int i=0, sum;    //This is some comment(embedded)
#
#   after conversion:
#       //This is some comment(embedded)
#       int i=0, sum;

import re
import os

#comm_re = re.compile(r"(\s*)(.*)(//.*)")

comm_re = re.compile(r"(\s*)(.*?)(//.*)")
ext_re  = re.compile(r"\.(cpp|h|hpp|c|icc)$")
out_ext = ".out"

TRUE  = 1
FALSE = 0

def comm_strip(file_name, keep_comment=TRUE):
    lines = file(file_name).readlines()
    out_lines = []

    out_filename = file_name + out_ext
    fout = open(out_filename, "w")

    for line in lines:
        match = comm_re.match(line.rstrip())

        if(match):
            if keep_comment:
                #print "%s%s" % (match.group(1), match.group(3))
                out_lines.append("%s%s\n" % (match.group(1), match.group(3)))
            if match.group(2):
                #print "%s%s" % (match.group(1), match.group(2).rstrip())
                out_lines.append("%s%s\n" % (match.group(1), match.group(2).rstrip()))
        else:
            #print line.rstrip()
            out_lines.append(line)

    out_lines.append("\n\n")
    fout.writelines(out_lines)
    print "File %s => %s" % (file_name, out_filename)
    print "-"*80

print os.getcwd()
file_names = os.listdir(".")
flag=TRUE

for file_name in file_names:
    match_ext = ext_re.search(file_name)

    if match_ext :
        comm_strip(file_name, flag)

print "Done!"

Comments on this post

brewbuck posts on Feb 21, 2007 at 12:28
What happens with code like this?

char *bad = "two slashes: //";
abhiwin posts on Mar 20, 2007 at 05:04
hey brewbuck,

thanks for posting ;-)

yes you are correct, i am not handling/checking the condition you have mentioned. i have simply coded that script for my own scenario in which there was no need of checking that ...

anyways may be some one will post in for that so that it will help us all.

Thanks

You need to create an account or log in to post comments to this site.


Click here to browse all 4861 code snippets

Related Posts