Skip to content

Instantly share code, notes, and snippets.

@shanecandoit
Created June 28, 2023 21:30
Show Gist options
  • Save shanecandoit/2ace0a40cd63f013f3f79d5e12708c2a to your computer and use it in GitHub Desktop.
Save shanecandoit/2ace0a40cd63f013f3f79d5e12708c2a to your computer and use it in GitHub Desktop.
Turn csv text into markdown tables and also into html
def csv_to_markdown_table(csv_string):
"""
Convert a csv style string to a markdown table string.
Args:
csv_string: The csv style string to convert.
Returns:
The markdown table string.
"""
rows = csv_string.split("\n")
table = ""
# header = []
for i, row in enumerate(rows):
row = row.strip()
if not row:
continue
cells = row.split(",")
table += "| " + " | ".join(cells) + " |\n"
if i == 0:
# header = cells
table += "| " + " | ".join(["---" for _ in cells]) + " |\n"
return table.strip()
sample = """name,age,state
alice,21,NY
bob,45,MO
charlie,13,CA
"""
want = """| name | age | state |
| --- | --- | --- |
| alice | 21 | NY |
| bob | 45 | MO |
| charlie | 13 | CA |"""
got = csv_to_markdown_table(sample)
print(got)
# | name | age | state |
# | --- | --- | --- |
# | alice | 21 | NY |
# | bob | 45 | MO |
# | charlie | 13 | CA |
print(want)
print(len(want), len(got))
assert want == got
def markdown_table_to_html(markdown_table):
"""
Convert a markdown table string to an HTML table string.
Args:
markdown_table: The markdown table string to convert.
Returns:
The HTML table string.
"""
html_table = ""
rows = markdown_table.split("\n")
for i, row in enumerate(rows):
row = row.strip()
if not row:
continue
cells = row.split(" | ")
dash_count = row.count("---")
print('dash_count', dash_count)
if dash_count == len(cells):
continue
html_row = "<tr>\n"
for cell in cells:
cell = cell.replace('|', '').strip()
if i == 0:
html_row += f" <th>{cell}</th>\n"
else:
html_row += f" <td>{cell}</td>\n"
html_row += "</tr>\n"
html_table += html_row
return html_table.strip()
html = markdown_table_to_html(got)
print(html)
want = """<tr>
<th>name</th>
<th>age</th>
<th>state</th>
</tr>
<tr>
<td>alice</td>
<td>21</td>
<td>NY</td>
</tr>
<tr>
<td>bob</td>
<td>45</td>
<td>MO</td>
</tr>
<tr>
<td>charlie</td>
<td>13</td>
<td>CA</td>
</tr>"""
assert want == html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment