Here's the updated code that only processes <svg> elements with width="648" and height="50":
import sys
from bs4 import BeautifulSoup
html_file_path = 'table.html'
tsv_file_path = 'table.tsv'
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)
try:
soup = BeautifulSoup(html_content, 'lxml')
except Exception as e:
print(f"Error parsing HTML: {e}", file=sys.stderr)
sys.exit(1)
output_tsv_lines = []
html_tables = soup.find_all('table')
if not html_tables:
print("No <table> elements found.", file=sys.stderr)
sys.exit(1)
for table_idx, html_table_element in enumerate(html_tables):
if len(html_tables) > 1:
output_tsv_lines.append(f"# --- Data from Table {table_idx + 1} ---")
else:
output_tsv_lines.append(f"# --- Combined Table and Rect Data ---")
table_headers_html = []
table_data_rows_html = []
rect_data_per_html_row = []
html_table_rows = html_table_element.find_all('tr')
is_first_row = True
current_num_html_cols = 0
for tr_element in html_table_rows:
current_row_cells_text = []
is_header_row_tr = False
# Extract cell data
cells = tr_element.find_all(['th', 'td'])
if not cells:
rect_data_per_html_row.append({
'w35': "NONE", 'x35': "NONE",
'w10': "NONE", 'x10': "NONE"
})
table_data_rows_html.append([])
continue
for cell_element in cells:
if cell_element.name == 'th':
is_header_row_tr = True
cell_text = cell_element.get_text(separator=" ", strip=True)
cell_text = cell_text.replace('\n', ' ').replace('\r', '').replace('\t', ' ')
current_row_cells_text.append(cell_text)
if is_first_row:
if is_header_row_tr:
table_headers_html = list(current_row_cells_text)
else:
table_headers_html = [''] * len(current_row_cells_text)
table_data_rows_html.append(current_row_cells_text)
current_num_html_cols = len(table_headers_html)
is_first_row = False
else:
table_data_rows_html.append(current_row_cells_text)
current_num_html_cols = max(current_num_html_cols, len(current_row_cells_text))
if len(table_headers_html) < current_num_html_cols:
table_headers_html.extend([''] * (current_num_html_cols - len(table_headers_html)))
# Process SVG with specific dimensions
svg_element_in_row = None
for svg in tr_element.find_all('svg'):
if svg.get('width') == '648' and svg.get('height') == '50':
svg_element_in_row = svg
break
row_rect_w35, row_rect_x35 = "NONE", "NONE"
row_rect_w10, row_rect_x10 = "NONE", "NONE"
if svg_element_in_row:
for rect_in_svg in svg_element_in_row.find_all('rect'):
next_sibling = rect_in_svg.find_next_sibling('text')
if next_sibling:
text_content = next_sibling.get_text(strip=True)
if text_content == "-35":
row_rect_w35 = rect_in_svg.get('width', "NONE")
row_rect_x35 = rect_in_svg.get('x', "NONE")
elif text_content == "-10":
row_rect_w10 = rect_in_svg.get('width', "NONE")
row_rect_x10 = rect_in_svg.get('x', "NONE")
rect_data_per_html_row.append({
'w35': row_rect_w35, 'x35': row_rect_x35,
'w10': row_rect_w10, 'x10': row_rect_x10
})
# Combine headers
combined_tsv_headers = list(table_headers_html)
combined_tsv_headers.extend(["width-35", "x-35", "width-10", "x-10"])
output_tsv_lines.append('\t'.join(combined_tsv_headers))
# Create output rows with 2-row shift for rect data
num_html_data_rows = len(table_data_rows_html)
num_output_data_rows = max(num_html_data_rows, len(rect_data_per_html_row) + 2)
for i in range(num_output_data_rows):
current_output_row_parts = []
# HTML table part
if i < num_html_data_rows:
html_part = table_data_rows_html[i]
current_output_row_parts.extend(html_part)
current_output_row_parts.extend([''] * (current_num_html_cols - len(html_part)))
else:
current_output_row_parts.extend([''] * current_num_html_cols)
# Rect data part (shifted by 2 rows)
rect_data_source_idx = i - 2
w35_val, x35_val, w10_val, x10_val = "", "", "", ""
if rect_data_source_idx >= 0 and rect_data_source_idx < len(rect_data_per_html_row):
rect_set = rect_data_per_html_row[rect_data_source_idx]
w35_val = rect_set['w35']
x35_val = rect_set['x35']
w10_val = rect_set['w10']
x10_val = rect_set['x10']
current_output_row_parts.extend([w35_val, x35_val, w10_val, x10_val])
output_tsv_lines.append('\t'.join(current_output_row_parts))
output_tsv_lines.append("")
# Write output
if not output_tsv_lines:
with open(tsv_file_path, 'w', encoding='utf-8'): pass
print(f"Created empty file '{tsv_file_path}'.")
else:
while output_tsv_lines and output_tsv_lines[-1] == "":
output_tsv_lines.pop()
try:
with open(tsv_file_path, 'w', encoding='utf-8') as f:
f.write('\n'.join(output_tsv_lines))
f.write('\n')
print(f"Successfully wrote to '{tsv_file_path}'.")
except Exception as e:
print(f"Error writing output file: {e}", file=sys.stderr)
sys.exit(1)
Key changes:
- Added specific SVG dimension check:
if svg.get('width') == '648' and svg.get('height') == '50'
- Only processes rects within SVGs that match these exact dimensions
- Maintains all other functionality (2-row shift, "NONE" for missing rects, etc.)
The code will now only look for rectangles in SVGs that are exactly 648px wide and 50px tall, ignoring all other SVGs in the document.