如何利用Python将Markdown表转换为CSV

1,345 阅读1分钟

问题

给出以下存储在'my_file.md' 的Markdown表。

| 1     | 2   | 3    | 4    | 5    |
|-------|-----|------|------|------|
| 0     | 0   | 0    | 0    | 0    |
| 5     | 4   | 3    | 2    | 1    |
| alice | bob | carl | dave | emil |

🐍 Python挑战:如何将Markdown表转换为CSV文件 ?'my_file.csv'

解决方案

要在Python中一个Markdown表.md 文件转换为CSV文件,首先通过对打开的文件对象f.readlines() 方法读取Markdown表文件f ,通过沿着markdown表分隔符'|' 。对得到的列表进行清理(从行的角度),并将所有的行加入到一个单一的列表中。然后从列表中创建一个DataFrame并使用 [DataFrame.to_csv()](https://blog.finxter.com/pandas-dataframe-to_csv-method/)方法将其写入CSV文件。

下面的脚本中显示了一个例子,你可以用它来做你自己的转换练习,只需替换下面强调的文件内和文件外的名称。

import pandas as pd

# Convert the Markdown table to a list of lists
with open('my_file.md') as f:
    rows = []
    for row in f.readlines():
        
        # Get rid of leading and trailing '|'
        tmp = row[1:-2]

        # Split line and ignore column whitespace
        clean_line = [col.strip() for col in tmp.split('|')]

        # Append clean row data to rows variable
        rows.append(clean_line)

    # Get rid of syntactical sugar to indicate header (2nd row)
    rows = rows[:1] + rows[2:]


print(rows)
df = pd.DataFrame(rows)
df.to_csv('my_file.csv', index=False, header=False)


由此产生的CSV文件'my_file.csv'

1,2,3,4,5
0,0,0,0,0
5,4,3,2,1
alice,bob,carl,dave,emil