Here’s an updated version that
- keeps the rectangle data as extra columns (
width-35, x-35, width-10, x-10) and
- starts filling those columns two rows below the corresponding table rows (so the first two table rows have empty values in the new columns).
import sys
from bs4 import BeautifulSoup
html_file_path = 'table.html'
tsv_file_path = 'table.tsv'
# -------------------------------------------------
# read and parse html
# -------------------------------------------------
try:
html_content = open(html_file_path, encoding='utf-8').read()
except FileNotFoundError:
print(f"Error: '{html_file_path}' not found.", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"Error reading '{html_file_path}': {e}", file=sys.stderr)
sys.exit(1)
try:
soup = BeautifulSoup(html_content, 'lxml')
except Exception as e:
print(f"Error parsing HTML: {e}", file=sys.stderr)
sys.exit(1)
# -------------------------------------------------
# collect rect data (-35 and -10)
# -------------------------------------------------
rects_minus_35 = []
rects_minus_10 = []
for r in soup.find_all('rect'):
nxt = r.find_next_sibling('text')
if not nxt:
continue
info = {'width': r.get('width', ''), 'x': r.get('x', '')}
txt = nxt.get_text(strip=True)
if txt == "-35":
rects_minus_35.append(info)
elif txt == "-10":
rects_minus_10.append(info)
# -------------------------------------------------
# build TSV lines
# -------------------------------------------------
tsv_lines = []
ROW_OFFSET = 2 # ← shift rect data two rows down
tables = soup.find_all('table')
if tables:
tsv_lines.append("# --- Combined Table & Rect Data ---")
for t_idx, tbl in enumerate(tables):
if len(tables) > 1:
tsv_lines.append(f"# --- Table {t_idx+1} ---")
# ---------- extract headers & rows ----------
headers = []
rows_data = []
first = True
for tr in tbl.find_all('tr'):
cells = tr.find_all(['td', 'th'])
row_vals = [
c.get_text(separator=" ", strip=True).replace('\n', ' ')
.replace('\r', '')
.replace('\t', ' ')
for c in cells
]
if first:
if tr.find('th'): # explicit header row
headers = row_vals
else: # no <th>; treat as data
headers = [''] * len(row_vals)
rows_data.append(row_vals)
first = False
else:
rows_data.append(row_vals)
num_html_cols = max(len(r) for r in rows_data) if rows_data else len(headers)
# ---------- final headers ----------
headers = headers or [''] * num_html_cols
headers += ["width-35", "x-35", "width-10", "x-10"]
tsv_lines.append('\t'.join(headers))
# ---------- combined row count ----------
max_rows = max(
len(rows_data),
len(rects_minus_35) + ROW_OFFSET,
len(rects_minus_10) + ROW_OFFSET
)
# ---------- emit combined rows ----------
for i in range(max_rows):
row = []
# table part
if i < len(rows_data):
row.extend(rows_data[i] + [''] * (num_html_cols - len(rows_data[i])))
else:
row.extend([''] * num_html_cols)
# rect -35 part (with offset)
j = i - ROW_OFFSET
if 0 <= j < len(rects_minus_35):
row.append(rects_minus_35[j]['width'])
row.append(rects_minus_35[j]['x'])
else:
row.extend(['', ''])
# rect -10 part (with offset)
if 0 <= j < len(rects_minus_10):
row.append(rects_minus_10[j]['width'])
row.append(rects_minus_10[j]['x'])
else:
row.extend(['', ''])
tsv_lines.append('\t'.join(row))
tsv_lines.append("") # blank line after each table
else:
print("No <table> elements found.", file=sys.stderr)
# -------------------------------------------------
# write TSV file
# -------------------------------------------------
if not tsv_lines:
print("No data to write.", file=sys.stderr)
open(tsv_file_path, 'w', encoding='utf-8').close()
else:
with open(tsv_file_path, 'w', encoding='utf-8') as f:
f.write('\n'.join(tsv_lines) + '\n')
print(f"Wrote combined data to '{tsv_file_path}'.")