Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mikeshi80
Last active April 15, 2024 22:17
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mikeshi80/5524036 to your computer and use it in GitHub Desktop.
Save mikeshi80/5524036 to your computer and use it in GitHub Desktop.
Extract the comments from the C/C++ style source code to the same name add .cmt ext name. Usage is python extractcomment.py topdir .ext1 .ext2 ... You can set the encoding to read and write file correctly. Reference the source here http://www.cppblog.com/luyulaile/archive/2012/12/03/195907.html
#!/usr/bin/env python
import sys
import re
import os.path
import codecs
import os
encoding = 'cp932'
def comment_finder(text):
pattern = re.compile( r'//.*?$|/\*.*?\*/', re.DOTALL | re.MULTILINE)
result = pattern.findall(text)
return result
def print_command(filename):
codefile = codecs.open(filename,'r', encoding)
commentfile = codecs.open(filename+".cmt",'w', encoding)
lines=codefile.read()
codefile.close()
#the list of comments
list_of_comments = comment_finder(lines)
for comment in list_of_comments:
#print comment[0:2]
if comment[0:2] == "//":
comment_to_write = comment[2:]
else:
comment_to_write = comment[2:-2]
if comment_to_write.endswith("\r"):
comment_to_write = comment_to_write[0:-1]
if len(comment_to_write)!=0:
commentfile.write(comment_to_write)
commentfile.write(os.linesep)
commentfile.close()
def visitor(filters, dirname, names):
mynames = filter(lambda n : os.path.splitext(n)[1].lower() in filters, names)
for name in mynames:
fname = os.path.join(dirname, name)
if not os.path.isdir(fname):
print_command(fname)
'''
Usage:
python extract.py topdir .ext1 [.ext2]
'''
if __name__ == "__main__":
topdir = sys.argv[1]
filters = sys.argv[2:]
os.path.walk(topdir, visitor, filters)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment