Okay, I understand the requirements now. We need to:
- Process each HTML
<table>.
- For each row (
<tr>) in the HTML table:
a. Extract its cell (<td>/<th>) data.
b. Look for an <svg> element within that specific table row.
c. Inside that <svg> (if found):
i. Try to find a <rect> immediately followed by <text>-35</text>. If found, get its width and x. If not, use "NONE" for both.
ii. Try to find a <rect> immediately followed by <text>-10</text>. If found, get its width and x. If not, use "NONE" for both.
d. This gives us one set of (width-35, x-35, width-10, x-10) values (or "NONE"s) for each HTML table row.
- When constructing the final TSV:
a. The HTML table data columns come first.
b. The "width-35", "x-35", "width-10", "x-10" columns are appended to the right.
c. The data for these rect-derived columns should appear shifted 2 rows down relative to the HTML table row they were extracted from. This means the rect data for HTML row 0 will appear on output row 2, HTML row 1 on output row 3, and so on. The first two output rows will have blank/empty values for these rect-derived columns.
This is a more complex alignment. Let's implement it.
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 if there's any rect data to process even without tables
all_svgs_global = soup.find_all('svg')
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) == "-35" or next_sibling_global.get_text(strip=True) == "-10"):
has_global_rect_data = True
break
if has_global_rect_data:
break
if not has_global_rect_data:
print("No <rect> data associated with -35 or -10 found either.", file=sys.stderr)
# Create empty file if requested
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 if not html_tables and not has_global_rect_data else 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 = [] # List of lists (each inner list is a row of cell texts)
# To store rect data corresponding to each HTML row
# Each item will be {'w35': val, 'x35': val, 'w10': val, 'x10': val}
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 for the current HTML row
cells = tr_element.find_all(['th', 'td'])
if not cells: # Skip empty tr
if is_first_row: # if first row is empty, we might not set num_html_cols
is_first_row = False # ensure it's not considered first anymore
# For rect data, an empty HTML row means no associated SVG.
rect_data_per_html_row.append({
'w35': "NONE", 'x35': "NONE",
'w10': "NONE", 'x10': "NONE"
})
table_data_rows_html.append([]) # Add an empty list to keep row count sync
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:
# No <th> in first row, treat as data, create blank headers
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))
# Ensure headers list is long enough if subsequent rows are longer
if len(table_headers_html) < current_num_html_cols:
table_headers_html.extend([''] * (current_num_html_cols - len(table_headers_html)))
# --- Process SVG within this specific <tr> ---
svg_element_in_row = tr_element.find('svg') # Find first SVG in the row
row_rect_w35, row_rect_x35 = "NONE", "NONE"
row_rect_w10, row_rect_x10 = "NONE", "NONE"
if svg_element_in_row:
# Find first -35 rect
found_35_in_svg = False
for rect_in_svg in svg_element_in_row.find_all('rect'):
next_sibling = rect_in_svg.find_next_sibling('text')
if next_sibling and next_sibling.get_text(strip=True) == "-35":
row_rect_w35 = rect_in_svg.get('width', "NONE")
row_rect_x35 = rect_in_svg.get('x', "NONE")
found_35_in_svg = True
break
# Find first -10 rect
found_10_in_svg = False
for rect_in_svg in svg_element_in_row.find_all('rect'):
next_sibling = rect_in_svg.find_next_sibling('text')
if next_sibling and next_sibling.get_text(strip=True) == "-10":
row_rect_w10 = rect_in_svg.get('width', "NONE")
row_rect_x10 = rect_in_svg.get('x', "NONE")
found_10_in_svg = True
break
rect_data_per_html_row.append({
'w35': row_rect_w35, 'x35': row_rect_x35,
'w10': row_rect_w10, 'x10': row_rect_x10
})
# --- End of processing <tr> elements for one table ---
# If table_headers_html is still empty (e.g. table had no <tr> or only empty <tr> with no <th>)
# and table_data_rows_html has data, derive num_html_cols.
if not table_headers_html and table_data_rows_html:
if any(table_data_rows_html): # Check if there's any actual data
current_num_html_cols = max(len(r) for r in table_data_rows_html if r) # Max length of non-empty rows
table_headers_html = [''] * current_num_html_cols
else: # All rows were empty or no rows
current_num_html_cols = 0 # No HTML columns
# Combine headers for TSV output
combined_tsv_headers = list(table_headers_html)
rect_column_headers = ["width-35", "x-35", "width-10", "x-10"]
combined_tsv_headers.extend(rect_column_headers)
output_tsv_lines.append('\t'.join(combined_tsv_headers))
# Determine total number of output rows, considering the 2-row shift for rect data
num_html_data_rows = len(table_data_rows_html)
# Rect data starts effectively 2 rows later. Its length is tied to num_html_data_rows.
# The total output rows will be num_html_data_rows if no rect data,
# or num_html_data_rows + 2 if rect data exists and needs to extend.
# More accurately, it's the max of (num_html_data_rows) and (len(rect_data_per_html_row) + 2 (for the shift))
# Since len(rect_data_per_html_row) == num_html_data_rows (or len(html_table_rows)),
# this simplifies to:
num_output_data_rows = num_html_data_rows
if rect_data_per_html_row: # If we processed any rects (even if all were "NONE")
num_output_data_rows = max(num_html_data_rows, len(rect_data_per_html_row) + 2 if len(rect_data_per_html_row) > 0 else 0 )
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)
# Pad if this HTML row is shorter than num_html_cols
current_output_row_parts.extend([''] * (current_num_html_cols - len(html_part)))
else:
# This case handles rows needed for shifted rect data beyond HTML table length
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 = "", "", "", "" # Default for rows 0, 1 or out of bounds
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("") # Blank line after each table's combined data
# --- End of processing all tables ---
# If no HTML tables were found, but user might still want global rects (less likely with this structure)
# This part is mostly defensive. The core logic above handles tables.
if not html_tables and not output_tsv_lines: # If absolutely nothing was processed
print("No HTML tables found to process. Checking for standalone SVG rect data (unlikely to be desired format).", file=sys.stderr)
# This case is complex if we were to try and format standalone rects with a shift.
# For now, if no tables, it means no primary data structure.
# The initial check for `html_tables` already handles creating an empty file if no data.
# --- Write the TSV output to a file ---
if not output_tsv_lines:
print("No data found to write to TSV (after processing).", 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(1)
else:
# Remove trailing blank lines if any before writing
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))
if output_tsv_lines: # Add a final newline if content was written
f.write('\n')
print(f"Successfully converted data from '{html_file_path}' to '{tsv_file_path}'.")
except Exception as e:
print(f"Error writing output file '{tsv_file_path}': {e}", file=sys.stderr)
sys.exit(1)
Key Changes and Logic:
-
Rect Data Collection per HTML Row:
rect_data_per_html_row is a list created for each HTML table.
- As we iterate through each
<tr> of the HTML table:
- We find the first
<svg> element within that <tr>.
- Inside this SVG, we search for the first
<rect> followed by <text>-35</text> and the first for "-10".
- If found, their
width and x are stored. If not, "NONE" is stored.
- This dictionary
{'w35': ..., 'x35': ..., 'w10': ..., 'x10': ...} is appended to rect_data_per_html_row. So, rect_data_per_html_row[j] contains the rect info for html_table_rows[j].
-
Determining Number of HTML Columns (current_num_html_cols):
- This is now more carefully tracked to handle tables without
<th> or tables where data rows might have more columns than an initial headerless row.
-
Determining Output Rows (num_output_data_rows):
- The total number of data rows in the output TSV needs to accommodate both the HTML table rows and the rect data which is shifted 2 rows down.
- It's calculated as
max(num_html_data_rows, len(rect_data_per_html_row) + 2). Since len(rect_data_per_html_row) will be equal to num_html_data_rows (or len(html_table_rows)), this ensures that if there's rect data, the output table is long enough to show it even if it extends past the original HTML table due to the shift.
-
Constructing Output Rows with Shift:
- When looping
i from 0 to num_output_data_rows - 1:
- HTML Part: Data is taken from
table_data_rows_html[i] if i is within bounds. Otherwise, blank cells are used.
- Rect Part:
- The index to fetch from
rect_data_per_html_row is rect_data_source_idx = i - 2.
- If
rect_data_source_idx is negative (i.e., for output rows 0 and 1), blank values ("") are used for the rect columns.
This version directly ties the SVG search and rect data extraction to each row of the HTML table and then applies the 2-row downward shift during the final TSV assembly.