python-highlight

## c/c++ high-light by tianzimk 2016-3-20 

def high_light(strpath):
	line_num = getline(strpath)
	fr = open(strpath, "r")
	fw = open(strpath + ".html","w")

	fw.write("<pre>")
	fw.write("<span style=\"font-family: Consolas\">")
	fw.write("<table>")
	fw.write("<td>")
	for i in range(line_num):
		fw.write("<div>%s</div>"%(i))
	fw.write("</td>")
	fw.write("<td>")
	index = 0;
	while True:
		line = fr.readline()
		if line:
			line = line.replace(" "," ")
			line = line.replace("\n"," ")
			line = line.replace("\t","    ")
	
			if index % 2 == 0:
				fw.write("<div style=\"background-color:#eeeeee\"/>")
			else:
				fw.write("<div style=\"background-color:#f8f8f8\"/>")
			index = index + 1

			line = line.replace("\"",""")
			line = line.replace("<","<")
			line = line.replace(">",">")
			line = magic_note(line)
				
			key_list_red = ["#include","#define","NULL","true","false","#ifndef","#endif"]
			for key in key_list_red:
				if has_key(line,key):
					line = replace_key_word(line,key,"#ff0000")

			key_list = ["int","float","double","void","cout","endl","using","namespace","unsigned","short","std","this","return",\
			"if","else","bool","new","string","static","char","extern","const","struct","class","public","private","enum"]
			for key in key_list:
				if has_key(line,key):
					line = replace_key_word(line,key,"#0000ff")
		
			fw.write(line)
		else:
			break
	fw.write("</td>")
	fw.write("</table>")
	fw.write("</span>")
	fw.write("</pre>")
	fw.close()
	fr.close() 

def has_key(str,key_word):
	pos = str.find(key_word)
	if pos >= 0:
		if pos + len(key_word) < len(str):
			if str[pos + len(key_word)].isdigit() | str[pos + len(key_word)].isalpha():
				return False
		if pos > 0:
			if str[pos-1].isdigit() | str[pos-1].isalpha():
				return False	
		return True
	return False

def getline(strpath):
	fr = open(strpath, "r")
	index = 0
	while True:
		line = fr.readline()
		if line:
			index = index + 1
		else:
			fr.close()
			return index

def magic_note(str):
	pos = str.find("//")
	if pos >= 0:
		return str[0:pos] + "<span style=\"color: #008000\">" + str[pos:] + "</span>"
	return str

def replace_key_word(str,str_key,color):
	pos = str.find("//")
	if pos == 0:
		return str
	elif pos > 0:
		str_left = str[0:pos]
		str_left = str_left.replace(str_key,"<span style=\"color: %s\">"%(color) + str_key + "</span>")
		return str_left + str[pos:]
	else:
		str_replace = "<span style=\"color: %s\">"%(color) + str_key + "</span>"
		return str.replace(str_key,str_replace)

if __name__ == "__main__":
	strpath = input("input the *.h or *.cpp file: ")
	high_light(strpath)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值