表格填補是RAG分塊中常見的需求,但不同格式的表格處理方式有所不同。本文將對 Markdown、HTML、Excel 的合并單元格進行說明,并給出 Python 示例,演示如何解析和填補。
1. Markdown 表格
Markdown 只能用空值表示合并單元格。(只有列方向的合并表格)
示例
| 姓名 | 科目 | 分數 |
|------|------|------|
| 張三 | 數學 | 90 |
| | 語文 | 85 |
| 張三 | 英語 | 88 |
| 李四 | 數學 | 92 |
| | 語文 | 80 |
Python 解析
import pandas as pd
from io import StringIOmarkdown_table = """
姓名|科目|分數
張三|數學|90
|語文|85
張三|英語|88
李四|數學|92
|語文|80
"""df = pd.read_csv(StringIO(markdown_table), sep="|")
df['姓名'] = df['姓名'].ffill()
print(df)
輸出
姓名 科目 分數
0 張三 數學 90
1 張三 語文 85
2 張三 英語 88
3 李四 數學 92
4 李四 語文 80
2. HTML 表格
HTML 可以用 rowspan
和 colspan進行填補
。
示例
<table><tr><td rowspan="2">張三</td><td>數學</td><td>90</td></tr><tr><td>語文</td><td>85</td></tr><tr><td rowspan="2">李四</td><td>數學</td><td>92</td></tr><tr><td>語文</td><td>80</td></tr>
</table>
Python 解析(BeautifulSoup + 填補 rowspan)
from bs4 import BeautifulSouphtml = """
<table><tr><td rowspan="2">張三</td><td>數學</td><td>90</td></tr><tr><td>語文</td><td>85</td></tr><tr><td rowspan="2">李四</td><td>數學</td><td>92</td></tr><tr><td>語文</td><td>80</td></tr>
</table>"""soup = BeautifulSoup(html, "html.parser")
rows = soup.find_all("tr")# 構建空表格
table = []
for r, row in enumerate(rows):cols = row.find_all("td")current_row = []for col in cols:value = col.get_text()rowspan = int(col.get("rowspan", 1))colspan = int(col.get("colspan", 1))current_row.append({"value": value, "rowspan": rowspan, "colspan": colspan})table.append(current_row)# 計算總列數
max_cols = max(sum(cell["colspan"] for cell in row) for row in table)# 初始化填補后的表格
filled_table = [[None]*max_cols for _ in range(len(table))]# 填充邏輯
for r, row in enumerate(table):c_idx = 0for cell in row:# 找到當前行可用位置while filled_table[r][c_idx] is not None:c_idx += 1# 填充 rowspan 和 colspanfor i in range(cell["rowspan"]):for j in range(cell["colspan"]):filled_table[r+i][c_idx+j] = cell["value"]c_idx += cell["colspan"]# 打印結果
for r in filled_table:print(r)
輸出
['張三', '數學', '90']
['張三', '語文', '85']
['李四', '數學', '92']
['李四', '語文', '80']
3. Excel 表格
Excel 合并單元格讀取后用 pandas 填補即可。
姓名 | 科目 | 分數 |
---|---|---|
張三 (合并兩行) | 數學 | 90 |
語文 | 85 | |
李四 (合并兩行) | 數學 | 92 |
語文 | 80 |
import pandas as pddf = pd.read_excel("example.xlsx")
df['姓名'] = df['姓名'].ffill()
print(df)
輸出
姓名 科目 分數
0 張三 數學 90
1 張三 語文 85
2 李四 數學 92
3 李四 語文 80
4. Word 表格合并單元格特點
在 Word 文檔里,表格同樣支持“合并單元格”,類似于 Excel,但它有自己的特點:
可以 合并行(rowspan) 或 合并列(colspan)
合并單元格的內容只保留左上角的單元格,其余單元格為空
Python 讀取 Word 表格通常用
python-docx
庫讀取后的表格數據需要手動填補合并單元格的空值,類似 Excel
示例 Word 表格
姓名 | 科目 | 分數 |
---|---|---|
張三 (合并兩行) | 數學 | 90 |
語文 | 85 | |
李四 (合并兩行) | 數學 | 92 |
語文 | 80 |
Python 解析 Word 表格并填補
from docx import Documentdoc = Document("example.docx")
table = doc.tables[0]# 先讀取表格內容
data = []
for row in table.rows:data.append([cell.text.strip() if cell.text.strip() else None for cell in row.cells])# 填補合并單元格(垂直填充)
for col in range(len(data[0])):last_val = Nonefor row in data:if row[col]:last_val = row[col]else:row[col] = last_valfor row in data:print(row)
輸出
['張三', '數學', '90']
['張三', '語文', '85']
['李四', '數學', '92']
['李四', '語文', '80']
結論:
Markdown:用空值表示合并單元格,再
ffill()
HTML:用
rowspan
,需要邏輯填補Excel:合并單元格讀取后是 NaN,用
ffill()
Word 表格合并單元格讀取后非首單元格為
None
可以用 逐列垂直填充(類似 Excel
ffill()
)Python 最常用庫是
python-docx