mercredi 29 juin 2016

How can I split code-blocks into a list?

I would like to split the contents of a CSS file into code blocks and push each block into a list using Python 3.5.

Given this CSS:

h1 {color: #333, background-color: transparent}
h2 {
  font-weight:300
}
h3
{
  font-weight: 200
}

Straight away we can tell that it has multiple styles and / or types of indentation meaning the CSS has to be tidied to get this:

h1 {
  color: #333,background-color: transparent;
}

h2 {
  font-weight: 300;
}

h3 {
  font-weight: 200;
}

How can I use Python to read the tidied string of CSS and push every block inside it into a Python list like this:

styles = [
  "h1 {n  color: #333,background-color: transparent;n}",
  "h2 {n  font-weight: 300;n}",
  "h3 {n  font-weight: 200;n}"
]

I would also like to point out that RegExp is not really my forte and I'm not quite sure what RegEx to use, but I was thinking that I could use RegExp & [].split(...); together to achieve this.

Possibly even use RegExp to eliminate the need to tidy the stylesheet before splitting the code-blocks in it.

I've been researching this question but that did not help either.

Aucun commentaire:

Enregistrer un commentaire