Skip to content

Instantly share code, notes, and snippets.

@giampaolo44
Last active April 8, 2018 23:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giampaolo44/ca437c66057413c2c20449fb628e69ee to your computer and use it in GitHub Desktop.
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
"""
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("<","&lt;")# replace all < with &lt;
code_tmp = code_tmp.replace(">","&gt;")# replace all > with &gt;
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(" ","&nbsp;&nbsp;")#then replace all double space indents with two &nbsp;
open(output_file, 'w').write(code)
@giampaolo44
Copy link
Author

giampaolo44 commented Apr 3, 2018

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.
code_file
htmlcode_html

@giampaolo44
Copy link
Author

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