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

import sys

bhasCCommentBegin = False

# @brief: Handle Comment of Cpp Language
#  The comment of cpp style will be delete if exist lines[i]
def HandleCPlusPlusComment(lines,i):
	index = lines[i].find("//")
	if index !=-1:
		lines[i]=lines[i][0:index]
		lines[i]+="\r\n"
		
# @brief: Handle Comment of C Language
# @ret -1:the Line is Comment Line,should delete this line
# @ret -2:Only begin Comment found in this Line
# @ret  0:Not find CComment 
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:]
					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:] #continue look for comment
			else:
				return -1 #should delete this


# @brief: Remove Comment  of file
# Check if there are C style comment firstly,and then check cpp style comment
# At last  print the result handled
def RemoveComment(file):
	global bhasCCommentBegin
	f = open(file,"r")
	lines = f.readlines()
	f.close()
	length =len(lines)
	i=0
	while i<length:
		ret = HandleCComment(lines,i)
		if ret == -1:
			if bhasCCommentBegin == False:
				print "There must be some wrong"
			del lines[i]
			i -= 1
			length -= 1
		elif ret== 0:
			HandleCPlusPlusComment(lines,i)
		else:
			pass
		i+=1

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

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


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值