## 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)
python-highlight
最新推荐文章于 2024-10-28 15:57:22 发布