Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion grab.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,20 @@ def get_data(self):


def strip_tags(html):
"""Function to strip HTML tags, but preserve <pre> and <code> tags for code snippets."""
s = MLStripper()
s.feed(html)
return s.get_data()

stripped_html = s.get_data()

# Handle <pre> and <code> tags manually for code snippets
stripped_html = stripped_html.replace('<pre>', '\n.. code-block:: python\n\n ')
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It won't always be Python code. There are others using julia, c, ...

Also, wouldn't need to indent all the lines to the same column to work?

stripped_html = stripped_html.replace('</pre>', '\n')
stripped_html = stripped_html.replace('<code>', '`')
stripped_html = stripped_html.replace('</code>', '`')

return stripped_html


def remove_indent(text):
"""Removes leading and trailing spaces from each line in the text."""
Expand All @@ -51,6 +62,7 @@ def remove_indent(text):


def html2rst_allign_post(text):
"""Converts HTML content into reStructuredText (rst) format, handling code snippets."""
if not text:
raise ValueError("Empty post!")

Expand All @@ -60,8 +72,17 @@ def html2rst_allign_post(text):
if len(lines) < 2:
lines = '\n'.join(lines).replace("br>", "newline>\n").replace("/p>", "/pline>\n").splitlines()
lines = [x.replace("newline>", "br>").replace("/pline>","/p>") for x in lines]

# Insert teaser marker
lines.insert(3, "<!-- TEASER_END -->")

# Convert <pre> and <code> HTML tags into rst code block formatting
text_with_code_blocks = text.replace('<pre>', '\n.. code-block:: python\n\n ')
text_with_code_blocks = text_with_code_blocks.replace('</pre>', '\n')
text_with_code_blocks = text_with_code_blocks.replace('<code>', '`')
text_with_code_blocks = text_with_code_blocks.replace('</code>', '`')

lines = text_with_code_blocks.splitlines()
lines = [" " + x.strip() for x in lines]
lines = [".. raw:: html", ""] + lines

Expand Down