Here's the fully updated code that addresses your requirements:
- Processes all
<rect> elements inside <svg>
- Checks for associated
<text> elements with -35 or -10
- Marks
width and x as "NONE" if no valid text is found
- Aligns rect data 2 rows below table data
import sys
from bs4 import BeautifulSoup
html_file_path = 'table.html'
tsv_file_path = 'table.tsv'
# --- File Reading Section ---
try:
with open(html_file_path, 'r', encoding='utf-8') as f:
html_content = f.read()
except FileNotFoundError:
print(f"Error: Input file '{html_file_path}' not found.", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"Error reading file '{html_file_path}': {e}", file=sys.stderr)
sys.exit(1)
# --- HTML Parsing Section ---
try:
soup = BeautifulSoup(html_content, 'lxml')
except Exception as e:
print(f"Error parsing HTML: {e}", file=sys.stderr)
sys.exit(1)
# --- Rect Processing Section ---
rects_minus_35 = []
rects_minus_10 = []
for rect in soup.find_all('rect'):
# Always get width and x, default to "NONE" if missing
width = rect.get('width', 'NONE')
x = rect.get('x', 'NONE')
# Look for associated text
txt = rect.find_next_sibling('text')
text_content = txt.get_text(strip=True) if txt else ''
# Populate rect data based on text content
if text_content == "-35":
rects_minus_35.append({'width': width, 'x': x})
rects_minus_10.append({'width': 'NONE', 'x': 'NONE'}) # No -10 match
elif text_content == "-10":
rects_minus_35.append({'width': 'NONE', 'x': 'NONE'}) # No -35 match
rects_minus_10.append({'width': width, 'x': x})
else:
# No match found for -35 or -10
rects_minus_35.append({'width': 'NONE', 'x': 'NONE'})
rects_minus_10.append({'width': 'NONE', 'x': 'NONE'})
# --- Table Processing Section ---
tsv_lines = []
tables = soup.find_all('table')
# --- Main Data Combination Section ---
if tables:
for ti, table in enumerate(tables):
tsv_lines.append(f"# --- Combined Table {ti+1} and Rect Data ---")
# Extract table headers and rows
rows = table.find_all('tr')
html_headers = []
html_rows = []
num_html_cols = 0
first_row = True
for r in rows:
cells = r.find_all(['th', 'td'])
texts = [c.get_text(" ", strip=True).replace('\t', ' ') for c in cells]
if first_row:
if r.find('th'):
html_headers = texts[:]
else:
html_headers = [''] * len(texts)
html_rows.append(texts)
num_html_cols = len(html_headers)
first_row = False
else:
html_rows.append(texts)
num_html_cols = max(num_html_cols, len(texts))
if not html_headers:
num_html_cols = max((len(r) for r in html_rows), default=0)
html_headers = [''] * num_html_cols
# Build final header
combined_headers = html_headers[:]
if rects_minus_35 or rects_minus_10:
combined_headers += ["width-35", "x-35", "width-10", "x-10"]
tsv_lines.append("\t".join(combined_headers))
# Calculate max rows including 2-row shift for rects
max_html = len(html_rows)
max_rects = max(len(rects_minus_35), len(rects_minus_10))
max_rows = max(max_html, max_rects) + 2 # Add 2-row shift
for i in range(max_rows):
row_parts = []
# HTML part
if i < max_html:
row = html_rows[i]
row_parts.extend(row + [''] * (num_html_cols - len(row)))
else:
row_parts.extend([''] * num_html_cols)
# Rect part (shifted down by 2 rows)
if i >= 2 and (i - 2) < max_rects:
idx = i - 2
row_parts.append(rects_minus_35[idx]['width'])
row_parts.append(rects_minus_35[idx]['x'])
row_parts.append(rects_minus_10[idx]['width'])
row_parts.append(rects_minus_10[idx]['x'])
else:
row_parts.extend(['NONE', 'NONE', 'NONE', 'NONE'])
tsv_lines.append("\t".join(row_parts))
tsv_lines.append("")
elif rects_minus_35 or rects_minus_10:
# Handle case with rects but no tables
tsv_lines.append("# --- Rect Data Only ---")
tsv_lines.append("width-35\tx-35\twidth-10\tx-10")
max_rects = max(len(rects_minus_35), len(rects_minus_10))
for i in range(max_rects):
parts = []
parts.append(rects_minus_35[i]['width'] if i < len(rects_minus_35) else 'NONE')
parts.append(rects_minus_35[i]['x'] if i < len(rects_minus_35) else 'NONE')
parts.append(rects_minus_10[i]['width'] if i < len(rects_minus_10) else 'NONE')
parts.append(rects_minus_10[i]['x'] if i < len(rects_minus_10) else 'NONE')
tsv_lines.append("\t".join(parts))
tsv_lines.append("")
else:
print("No table or rect data found.", file=sys.stderr)
# --- File Writing Section ---
if not tsv_lines:
with open(tsv_file_path, 'w', encoding='utf-8'): pass
print(f"Created empty file '{tsv_file_path}'.")
else:
while tsv_lines and tsv_lines[-1] == "":
tsv_lines.pop()
with open(tsv_file_path, 'w', encoding='utf-8') as f:
f.write("\n".join(tsv_lines))
f.write("\n")
print(f"Successfully wrote to '{tsv_file_path}'.")
✅ Key Features Implemented
| Feature | Description |
|---|
| Rect Detection | Processes all <rect> elements inside <svg> |
| Text Matching | Checks for associated <text> elements with content -35 or -10 |
| Fallback Values | Uses "NONE" for width and x if no valid text is found |
| Data Alignment | Shifts rect data 2 rows down from table data |
| TSV Structure | Maintains clean tab-separated values with headers and proper alignment |
📌 Example Output Format
# --- Combined Table 1 and Rect Data ---
Header1 Header2 width-35 x-35 width-10 x-10
Row1Col1 Row1Col2 NONE NONE NONE NONE
Row2Col1 Row2Col2 NONE NONE NONE NONE
NONE NONE NONE NONE
NONE NONE NONE NONE
Rect1Width Rect1X Rect1Width Rect1X Rect2Width Rect2X
This ensures:
- Table data appears first
- Two blank rows separate table and rect data
- Rect data appears with
"NONE" where no matching text was found
Let me know if you'd like to customize the "NONE" placeholder or adjust the row spacing!