Difference between revisions of "Team:EPF Lausanne/Project/Modelling/Code"
Line 198: | Line 198: | ||
<div class="col-md-12 col-centered"> | <div class="col-md-12 col-centered"> | ||
<h3>code2html</h3> | <h3>code2html</h3> | ||
− | <p>The following Python code allows to generate HTML (and CSS) code from source files in C++ and Python languages. It is based on <a href="http://pygments.org/" target="blank">Pygment</a>, a Python syntax highlighter. All | + | <p>The following Python code allows to generate HTML (and CSS) code from source files in C++ and Python languages. It is based on <a href="http://pygments.org/" target="blank">Pygment</a>, a Python syntax highlighter. All code in our Wiki is formatted using this script. |
<div class="highlight"><pre><span class="kn">from</span> <span class="nn">pygments</span> <span class="kn">import</span> <span class="n">highlight</span> | <div class="highlight"><pre><span class="kn">from</span> <span class="nn">pygments</span> <span class="kn">import</span> <span class="n">highlight</span> | ||
<span class="kn">from</span> <span class="nn">pygments.lexers</span> <span class="kn">import</span> <span class="n">PythonLexer</span> | <span class="kn">from</span> <span class="nn">pygments.lexers</span> <span class="kn">import</span> <span class="n">PythonLexer</span> |
Revision as of 15:42, 30 July 2015
Code
code2html
The following Python code allows to generate HTML (and CSS) code from source files in C++ and Python languages. It is based on Pygment, a Python syntax highlighter. All code in our Wiki is formatted using this script.
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.lexers import CppLexer
from pygments.formatters import HtmlFormatter
# C++ extensions
cpp = ["cpp","cxx","cc","h"]
# Python extensions
py = ["py"]
def load_file_as_sting(fname):
"""
Open the file FNAME and save all its content in an unformatted string
"""
content = ""
with open(fname,'r') as f: # Open the file (read only)
content = f.read() # Read file and store it in an unformatted string
# The file is automatically closed
return content
def save_string_as_file(fname,string):
"""
Save the unformatted string STRING into the file FNAME
"""
with open(fname,'w') as f: # Open the file (write only)
f.write(string)
# The file is automatically closed
def lexer(language):
"""
Return the lexer and the formatter for the appropriate language
"""
L = None
if language in py:
# Python Lexer
L = PythonLexer()
elif language in cpp:
# C++ Lexer
L = CppLexer()
else:
raise NameError("Invalid language.")
return L
def code_to_htmlcss(code,language):
"""
Transform CODE into html and css (separate files)
"""
# Obtain lexer
L = lexer(language)
# HtmlFormatter
HF = HtmlFormatter(style="monokai")
# Create html code
html = highlight(code,L,HF)
# Create css code
css = HF.get_style_defs('.highlight')
return html,css
def code_to_html(code,language):
"""
Transform CODE into html and css (all in the same file)
"""
# Obtain lexer
L = lexer(language)
# HtmlFormatter
HF = HtmlFormatter(full=True,style="monokai")
# Create fill html code
html = highlight(code,L,HF)
return html
import sys
if __name__ == "__main__":
"""
Command:
######################################
python code2html INPUTFILE [CSS]
######################################
INPUTFILE: name (with path) of the file to convert to html
CSS: write "true" in order to obtain separate .html and .css files ("false" by default)
"""
# Command line arguments
args = sys.argv
# Check command line arguments
ncla = len(args) # number of command line arguments
if ncla != 2 and ncla != 3 :
raise TypeError("Invalid number of command line arguments.")
css_bool = False
if ncla == 3 and args[-1].lower() == "true":
css_bool = True # Export css separately
# Input file
fname_code = sys.argv[1] # Name of the file containing the code to convert in html
# Input file extension
language = fname_code.split('.')[-1]
# Output files
fname_html = fname_code.split('.')[0] + ".html" # Name of the file where the html code will be stored
fname_css = fname_code.split('.')[0] + ".css" # Name of the file where the css code will be stored
# Save code into a unformatted string
code = load_file_as_sting(fname_code)
if css_bool == False: # Convert to standalone html
html = code_to_html(code,language)
else: # Convert to html and css separately
html,css = code_to_htmlcss(code,language)
# Save html
save_string_as_file(fname_html,html)
if css_bool == True:
# Save css
save_string_as_file(fname_css,css)
ODE Generator
class Reaction:
def __init__(self, reaction_, cst_name_, cst_value_, description_):
self.reaction = reaction_
self.cst_name = cst_name_
self.cst_value = cst_value_
self.description = description_
def __str__(self):
return "{}\n{} = {}\n{}".format(self.reaction,
self.cst_name,
str(self.cst_value),
self.description)
class ReactionParser:
def __init__(self, input_, sep_=":", comment_="#"):
self.sep = sep_
self.comment = comment_
self.file = open(input_, 'r') # TODO: OPEN SAFELY
self.reactions = []
self._load()
def __del__(self):
self.file.close()
def _load(self):
for line in self.file:
if line.strip() == "\n" or line.strip() == "": # Check for empty lines
continue
if len(line.strip()) != 0 and line.strip()[0] == self.comment: # Check for comments
continue
splitted = line.split(":")
if len(splitted) != 4:
raise ValueError('ReactionParser: problem with the input file (not enough arguments)')
reaction = Reaction(splitted[0].strip(),
splitted[1].strip(),
float(splitted[2].strip()),
splitted[3].strip())
self.reactions.append(reaction)
def print_reactions(self):
for reaction in self.reactions:
print(reaction)
print()
def reaction_table(self):
kin = []
for reaction in self.reactions:
splitted = reaction.reaction.split("->")
left = splitted[0].strip()
right = splitted[-1].strip()
kin.append( ([left, right], (reaction.cst_name, reaction.description, reaction.cst_value) ) )
return kin
if __name__ == "__main__":
myParser = ReactionParser("reactions.dat")
#myParser.load()
myParser.print_reactions()
kin = myParser.reaction_table()
print(kin)