码迷,mamicode.com
首页 > 编程语言 > 详细

python面试题--去除C++源文件里的注释

时间:2014-11-04 22:49:10      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:blog   ar   for   sp   文件   on   2014   log   ad   

import sys


def HandleCPlusPlusComment(lines,i):
	index = lines[i].find("//")
	if index !=-1:
		lines[i]=lines[i][0:index]
		lines[i]+="\r\n"



def HandleCComment(lines,i):
	global bhasCCommentBegin
	while True:
		if not bhasCCommentBegin:
			index = lines[i].find("/*")
			if index != -1:
				bhasCCommentBegin = True
				index2 = lines[i].find("*/",index+2)
				if index2 != -1:
					lines[i]=lines[i][0:index]+lines[i][index2+2:-1]
					bhasCCommentBegin = False #continue look for comment
				else:
					lines[i]=lines[i][0:index]  # only find "begin comment
					lines[i]+="\r\n"
					return -2
			else:
				return 0 #not find
		else:
			index2=lines[i].find("*/")
			if index2 !=-1:
				bhasCCommentBegin = False
				lines[i]=lines[i][index2+2:-1] #continue look for comment
			else:
				return -1 #should delete this



def RemoveComment(file):
	global bhasCCommentBegin
	f = open(file,"r")
	lines = f.readlines()
	leng =len(lines)
	i=0
	while i<leng:
		ret = HandleCComment(lines,i)
		if ret == -1:
			if bhasCCommentBegin == False:
				print "There must be some wrong"
			del lines[i]
			i -= 1
			leng -= 1
		elif ret== 0:
			HandleCPlusPlusComment(lines,i)
		else:
			pass
		i+=1
	Output(lines)


bhasCCommentBegin = False

def Output(lines):
	for line in lines:
		print line,



if __name__== '__main__':
	RemoveComment(sys.argv[1])
	

python面试题--去除C++源文件里的注释

标签:blog   ar   for   sp   文件   on   2014   log   ad   

原文地址:http://blog.csdn.net/smartfox80/article/details/40793915

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!