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)
# Check for standalone SVG rect data (unlikely but handled)
all_svgs_global = soup.find_all('svg', {'width': '648', 'height': '50'})
has_global_rect_data = False
if all_svgs_global:
for svg_element_global in all_svgs_global:
for rect_global in svg_element_global.find_all('rect'):
next_sibling_global = rect_global.find_next_sibling('text')
if next_sibling_global and (next_sibling_global.get_text(strip=True) in ("-35", "-10")):
has_global_rect_data = True
break
if has_global_rect_data:
break
if not has_global_rect_data:
print("No matching <svg> or <rect> data found.", file=sys.stderr)
try:
with open(tsv_file_path, 'w', encoding='utf-8') as f:
pass
print(f"Created empty file '{tsv_file_path}'.")
except Exception as e:
print(f"Error creating empty output file: {e}", file=sys.stderr)
sys.exit(0)
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("# --- 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).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 width="648" and height="50"
svg_element_in_row = tr_element.find('svg', {'width': '648', 'height': '50'})
w35, x35, w10, x10 = "NONE", "NONE", "NONE", "NONE"
if svg_element_in_row:
# Find -35 rect
for rect in svg_element_in_row.find_all('rect'):
text_tag = rect.find_next_sibling('text')
if text_tag and text_tag.get_text(strip=True) == "-35":
w35 = rect.get('width', "NONE")
x35 = rect.get('x', "NONE")
break
# Find -10 rect
for rect in svg_element_in_row.find_all('rect'):
text_tag = rect.find_next_sibling('text')
if text_tag and text_tag.get_text(strip=True) == "-10":
w10 = rect.get('width', "NONE")
x10 = rect.get('x', "NONE")
break
rect_data_per_html_row.append({'w35': w35, 'x35': x35, 'w10': w10, 'x10': x10})
if not table_headers_html and table_data_rows_html:
if any(table_data_rows_html):
current_num_html_cols = max(len(r) for r in table_data_rows_html if r)
table_headers_html = [''] * current_num_html_cols
# 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))
# Calculate output rows with 2-row shift
num_html_data_rows = len(table_data_rows_html)
num_output_rows = num_html_data_rows
if rect_data_per_html_row:
num_output_rows = max(num_html_data_rows, len(rect_data_per_html_row) + 2)
for i in range(num_output_rows):
current_parts = []
# HTML part
if i < num_html_data_rows:
html_part = table_data_rows_html[i]
current_parts.extend(html_part + [''] * (current_num_html_cols - len(html_part)))
else:
current_parts.extend([''] * current_num_html_cols)
# Rect part (shifted 2 rows down)
rect_idx = i - 2
w35_val, x35_val, w10_val, x10_val = "", "", "", ""
if 0 <= rect_idx < len(rect_data_per_html_row):
r = rect_data_per_html_row[rect_idx]
w35_val = r['w35']
x35_val = r['x35']
w10_val = r['w10']
x10_val = r['x10']
current_parts.extend([w35_val, x35_val, w10_val, x10_val])
output_tsv_lines.append('\t'.join(current_parts))
output_tsv_lines.append("") # Blank line after table
# Write output
if not output_tsv_lines:
print("No data found to write to TSV.", file=sys.stderr)
try:
with open(tsv_file_path, 'w', encoding='utf-8') as f:
pass
print(f"Created empty file '{tsv_file_path}'.")
except Exception as e:
print(f"Error creating empty file: {e}", file=sys.stderr)
sys.exit(1)
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) + '\n')
print(f"Successfully wrote data to '{tsv_file_path}'.")
except Exception as e:
print(f"Error writing file: {e}", file=sys.stderr)
sys.exit(1)
Key Changes
-
SVG Filtering:
-
Rect Extraction:
- Only searches for
<rect> elements inside qualifying SVGs.
- Uses
"NONE" if no matching rect or SVG is found.
-
Standalone SVG Check:
- In the case where no HTML tables are found, the code now also checks for standalone
<svg width="648" height="50"> elements with valid -35 or -10 text.
-
Code Simplification:
- Removed redundant checks and simplified logic for better readability while maintaining robustness.
This version ensures that only the relevant SVGs are processed and that the rect data is correctly associated with the appropriate HTML table rows, with a 2-row downward shift as requested.