Okay, I got it! You want to take the data from the HTML table(s) and append the width and x data from the rect elements (for both "-35" and "-10" texts) as new columns to the right of the existing table data.
This means if an HTML table has, say, 3 columns and 5 rows, and we find 4 rects associated with "-35" and 3 rects with "-10", the output TSV will have:
OriginalCol1 | OriginalCol2 | OriginalCol3 | width-35 | x-35 | width-10 | x-10
...and the number of rows will be the maximum of (HTML table rows, number of -35 rects, number of -10 rects). Empty cells will be used for padding where data doesn't exist for a particular row.
Here's the updated code:
python
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)
tsv_lines = []
# 1. Extract rect data first, as we'll need it for combining
rects_minus_35_data = []
rects_minus_10_data = []
all_rects = soup.find_all('rect')
if all_rects:
for rect in all_rects:
rect_info = {
'width': rect.get('width', ''),
'x': rect.get('x', '')
}
next_sibling = rect.find_next_sibling('text')
if next_sibling:
text_content = next_sibling.get_text(strip=True)
if text_content == "-35":
rects_minus_35_data.append(rect_info)
elif text_content == "-10":
rects_minus_10_data.append(rect_info)
else:
print("No <rect> elements found to extract data from.", file=sys.stderr)
# 2. Process HTML tables and combine with rect data
html_tables = soup.find_all('table')
if html_tables:
tsv_lines.append("# --- Combined Table and Rect Data ---")
for table_idx, table in enumerate(html_tables):
if len(html_tables) > 1:
tsv_lines.append(f"# --- Data from Table {table_idx+1} combined with Rects ---")
html_headers = []
html_rows_data = []
rows = table.find_all('tr')
first_row = True
num_html_cols = 0
for row in rows:
cells = row.find_all(['td', 'th'])
row_data = []
for cell in cells:
cell_text = cell.get_text(separator=" ", strip=True)
cell_text = cell_text.replace('\n', ' ').replace('\r', '').replace('\t', ' ')
row_data.append(cell_text)
if first_row:
# Check if the first row looks like headers (contains <th> or is the first <tr>)
# A more robust check might involve seeing if all cells are <th>
# For simplicity, we assume the first <tr> contains headers if <th> are present,
# or just treat it as data if only <td> are there.
# If it has <th>, it's definitely a header.
if row.find('th'):
html_headers = list(row_data) # Make a copy
num_html_cols = len(html_headers)
else: # No <th>, treat first row as data, generate empty headers
html_headers = [''] * len(row_data) # Placeholder if no actual <th>
num_html_cols = len(row_data)
html_rows_data.append(row_data)
first_row = False
else:
html_rows_data.append(row_data)
if not html_headers and not first_row: # Ensure num_html_cols is set even if no explicit headers
num_html_cols = max(num_html_cols, len(row_data))
# If html_headers was never populated (e.g. table with no <tr> or only empty <tr>)
# but html_rows_data has content, derive num_html_cols from data.
if not html_headers and html_rows_data:
num_html_cols = max(len(r) for r in html_rows_data) if html_rows_data else 0
html_headers = [''] * num_html_cols
# Combine headers
combined_headers = list(html_headers) # Start with HTML headers
if rects_minus_35_data or rects_minus_10_data: # Only add rect headers if rect data exists
combined_headers.extend(["width-35", "x-35", "width-10", "x-10"])
if combined_headers : # Only add header row if there's something to add
tsv_lines.append('\t'.join(combined_headers))
# Determine max rows for combining
max_rows = len(html_rows_data)
if rects_minus_35_data:
max_rows = max(max_rows, len(rects_minus_35_data))
if rects_minus_10_data:
max_rows = max(max_rows, len(rects_minus_10_data))
# Combine data rows
for i in range(max_rows):
current_row_parts = []
# HTML table part
if i < len(html_rows_data):
current_row_parts.extend(html_rows_data[i])
# Pad if this HTML row is shorter than others/header
current_row_parts.extend([''] * (num_html_cols - len(html_rows_data[i])))
else:
current_row_parts.extend([''] * num_html_cols) # Pad with empty if no HTML data for this row
# Rect -35 part (only if rect data was found and headers added)
if rects_minus_35_data or rects_minus_10_data:
if i < len(rects_minus_35_data):
current_row_parts.append(rects_minus_35_data[i]['width'])
current_row_parts.append(rects_minus_35_data[i]['x'])
else:
current_row_parts.extend(['', '']) # Pad
# Rect -10 part
if i < len(rects_minus_10_data):
current_row_parts.append(rects_minus_10_data[i]['width'])
current_row_parts.append(rects_minus_10_data[i]['x'])
else:
current_row_parts.extend(['', '']) # Pad
tsv_lines.append('\t'.join(current_row_parts))
tsv_lines.append("") # Blank line after each table's combined data
elif rects_minus_35_data or rects_minus_10_data:
# Case: No HTML tables, but rect data exists. Create a table just for rects.
tsv_lines.append("# --- Rect Data Only (No HTML Tables Found) ---")
combined_headers = ["width-35", "x-35", "width-10", "x-10"]
tsv_lines.append('\t'.join(combined_headers))
max_rows = 0
if rects_minus_35_data:
max_rows = max(max_rows, len(rects_minus_35_data))
if rects_minus_10_data:
max_rows = max(max_rows, len(rects_minus_10_data))
for i in range(max_rows):
current_row_parts = []
# Rect -35 part
if i < len(rects_minus_35_data):
current_row_parts.append(rects_minus_35_data[i]['width'])
current_row_parts.append(rects_minus_35_data[i]['x'])
else:
current_row_parts.extend(['', '']) # Pad
# Rect -10 part
if i < len(rects_minus_10_data):
current_row_parts.append(rects_minus_10_data[i]['width'])
current_row_parts.append(rects_minus_10_data[i]['x'])
else:
current_row_parts.extend(['', '']) # Pad
tsv_lines.append('\t'.join(current_row_parts))
tsv_lines.append("")
else:
print("No <table> elements found and no <rect> data to process.", file=sys.stderr)
# --- Write the TSV output to a file ---
if not 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 output file: {e}", file=sys.stderr)
sys.exit(1)
else:
# Remove trailing blank lines if any before writing
while tsv_lines and tsv_lines[-1] == "":
tsv_lines.pop()
try:
with open(tsv_file_path, 'w', encoding='utf-8') as f:
f.write('\n'.join(tsv_lines))
if 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:
Extract Rect Data First: The rects_minus_35_data and rects_minus_10_data lists are populated at the beginning. Each item in these lists is a dictionary {'width': '...', 'x': '...'}.
Process Each HTML Table: The code iterates through each <table> found in the HTML.
Extract HTML Headers and Rows:
It attempts to identify headers (<th>) from the first row of the HTML table. If no <th> are found, it treats the first row as data and uses empty strings as placeholders for HTML column headers.
num_html_cols stores the number of columns in the current HTML table.
Combine Headers:
The combined_headers list starts with the html_headers.
Then, "width-35", "x-35", "width-10", "x-10" are appended. These are only added if there's actual rect data to show.
Determine Maximum Rows:max_rows is calculated as the maximum length among the HTML table rows, the list of -35 rects, and the list of -10 rects. This ensures all data is included.
Combine Data Rows:
The code iterates max_rows times.
For each i (row index):
It takes data from html_rows_data[i] if i is within bounds, otherwise, it pads with empty strings for the HTML table part. It also pads if an HTML row is shorter than num_html_cols.
It then appends width and x from rects_minus_35_data[i] if available, otherwise pads with empty strings.
Similarly, it appends width and x from rects_minus_10_data[i] or pads.
These parts are joined by tabs to form the TSV row.
No HTML Tables Case: If no <table> elements are found, but rect data exists, it creates a TSV with only the rect data and its corresponding headers.
Output: The tsv_lines are written to the output file.
This approach should give you a single TSV where the rectangle data is effectively merged as new columns alongside the data from your HTML tables. If multiple HTML tables exist in the input, each will be processed and will have the same set of rect data appended to its right.