반응형
C/C++ 코드를 버전에 따라 다른 형식으로 작성해야 할 경우가 종종 있습니다.
예를 들어 어떤 경우에는 주석을 다 지우고 전달해야 하는 경우가 있는데~
이런 경우를 위해 파이썬으로 C/C++ 주석 지우는 코드를 만들어 봤습니다.
아래 코드에서 workingDir = "D:\TestFolder" 부분을 코드가 들어있는 최상위 폴더로 맞춰 주면 *.c, *.h 파일의 모든 주석을 지워줍니다.
C++ 코드 라면 AllFileList 부분에서 *.CPP 와 같은 확장자를 추가해 주면 됩니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fnmatch | |
import os | |
import re | |
import shutil | |
import time | |
def AllFileList(workingDir, *exts): | |
out = [] | |
for root, dirnames, filenames in os.walk(workingDir): | |
for ext in exts: | |
for filenameFullpath in fnmatch.filter(filenames, ext): | |
fullPath = os.path.join(root, filenameFullpath) | |
folderName = root.split(os.sep).pop() | |
out.append(fullPath) | |
return out | |
def deleteComment(strV): | |
strV = re.sub(r'\s*//.*?$', '', strV, flags=re.M) | |
strV = re.sub(r'/\*.*?\*/', '', strV, flags=re.S) | |
strV = re.sub(r'(^\s+$){1,}', '', strV, flags=re.M) | |
strV = re.sub(r'\n{3,}', '\n', strV) | |
return strV | |
def dirFileSplit(Fullpath): | |
workingDirFullpath = os.path.dirname(Fullpath) | |
filename = os.path.basename(Fullpath) | |
Spec = workingDirFullpath.split(os.sep).pop() | |
return workingDirFullpath, filename, Spec | |
if __name__ == '__main__': | |
workingDir = "D:\TestFolder" | |
workingDir_mod = workingDir + "_mod_" + time.strftime("%Y%m%d") | |
# d = datetime.datetime('%Y%m%d') | |
shutil.rmtree(workingDir_mod, ignore_errors=True) | |
os.mkdir(workingDir_mod) | |
outList = AllFileList(workingDir, '*.c', '*.h') | |
for filenameFullpath in outList: | |
modfilename = filenameFullpath.replace(workingDir, workingDir_mod) | |
fop = open(filenameFullpath, "r") | |
data = fop.read() | |
fop.close() | |
datamod = deleteComment(data) | |
workingDirFullpath, filename, Spec = dirFileSplit(modfilename) | |
if not os.path.isdir(workingDirFullpath): | |
os.mkdir(workingDirFullpath) | |
fw = open(modfilename, "w+") | |
fw.write(datamod) | |
fw.close() | |
print "------------- All End -------------" | |
반응형
'programming language > Python' 카테고리의 다른 글
chardet 을 활용한 텍스트 파일 encoding 확인 (0) | 2015.05.08 |
---|---|
Python 실행 파일 만들기 cx_Freeze (0) | 2015.01.10 |
Python GraphViz 모듈 (0) | 2014.12.28 |
윈도우용 Python 모듈 모음 (0) | 2014.12.27 |
Python 을 사용한 MS Word Generation (0) | 2014.12.22 |
Python Cartesian Product (0) | 2014.12.05 |
Python Computer Algebra System(CAS) package sympy (0) | 2014.12.03 |
Python Pyzo, IEP (0) | 2014.12.03 |
댓글