Got it! You want to append the rect data (width and x for "-35" and "-10") as new columns to the right of each row of the HTML table data.
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)
# Extract HTML table data
table_rows = []
html_tables = soup.find_all('table')
if html_tables:
for table in html_tables:
rows = table.find_all('tr')
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)
table_rows.append(row_data)
else:
print("No <table> elements found.", file=sys.stderr)
# Extract rect data for "-35" and "-10"
rects_minus_35 = []
rects_minus_10 = []
rects = soup.find_all('rect')
for rect in rects:
rect_data = {
'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.append(rect_data)
elif text_content == "-10":
rects_minus_10.append(rect_data)
# Determine max rows needed
max_rows = max(len(table_rows), len(rects_minus_35), len(rects_minus_10))
# Pad table rows if needed
num_table_cols = max(len(r) for r in table_rows) if table_rows else 0
for _ in range(max_rows - len(table_rows)):
table_rows.append([''] * num_table_cols)
# Pad rect lists if needed
def pad_rect_list(rect_list, length):
while len(rect_list) < length:
rect_list.append({'width': '', 'x': ''})
pad_rect_list(rects_minus_35, max_rows)
pad_rect_list(rects_minus_10, max_rows)
# Prepare TSV lines
tsv_lines = []
# Header row: original table headers + new rect columns
if table_rows:
header = table_rows[0]
else:
header = []
header += ['width-35', 'x-35', 'width-10', 'x-10']
tsv_lines.append('\t'.join(header))
# Data rows
start_idx = 1 if table_rows else 0 # skip header if exists
for i in range(max_rows):
row = []
if i < len(table_rows):
row = table_rows[i]
else:
row = [''] * num_table_cols
# Pad row if shorter than header cols (before rect columns)
if len(row) < num_table_cols:
row += [''] * (num_table_cols - len(row))
rect_35 = rects_minus_35[i]
rect_10 = rects_minus_10[i]
row += [rect_35['width'], rect_35['x'], rect_10['width'], rect_10['x']]
tsv_lines.append('\t'.join(row))
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:
try:
with open(tsv_file_path, 'w', encoding='utf-8') as f:
f.write('\n'.join(tsv_lines))
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)