Last active
April 8, 2018 23:36
-
-
Save giampaolo44/ca437c66057413c2c20449fb628e69ee to your computer and use it in GitHub Desktop.
Turn a snippet or a piece of code into something that can be pasted and displayed into an html page
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
""" | |
Turn a piece of python code into an html piece that respects indentation and CR. | |
input: fileName, [default = code_file] | |
output: fileName, [default = HtmlCode.html] | |
file_type: file_type, [default = txt] | |
""" | |
import argparse | |
parser = argparse.ArgumentParser(description="Crea l'html di un file di codice.") | |
parser.add_argument('-i', metavar='input_file', type=str, default="code_file") #input_file name | |
parser.add_argument('-o', metavar='output_file', type=str, default="HtmlCode.html") #output_file name | |
parser.add_argument('-t', metavar='file_type',type=str,default='txt') | |
args = parser.parse_args() | |
input_file=str(args.i) | |
output_file=str(args.o) | |
file_type=str(args.t) | |
code = "<code>"#open the new file with a <code> tag | |
code_tmp = open(input_file).read()#import the file | |
if file_type == "html": | |
code_tmp = code_tmp.replace("<","<")# replace all < with < | |
code_tmp = code_tmp.replace(">",">")# replace all > with > | |
code += code_tmp | |
code += "</code>\n"#close the new file with a </code> tag | |
code = code.replace("\n","<br>\n")#start by replacing all CR with <br>CR | |
code = code.replace(" "," ")#then replace all double space indents with two | |
open(output_file, 'w').write(code) |
What if the code we want to display on an html page is actually itself html? Added support for it: added file type, where only html would change the behavior and therefore the results of the conversion.
Also changed the indent rule, whereas now it replaces double spaces instead than the typical 4 spaces indents (that come with Python code, at least with my editor). It's sub-optimal: it would be better to count for sets of continuous spaces >2 and replace each of them with a corresponding series of
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm learing to code, and taking my notes into html. I got tired of reformatting each piece of code into html, so decided to write a snippet that could do it for me.
Attached are an example of input file, and the resulting output.