Certainly! Here's the updated code that lists the width and x attributes of the rect elements with text "-35" and "-10" together with the other table data, instead of separately. The rect data will be appended as additional rows after the HTML tables, with clear headers indicating which rects correspond to "-35" and which to "-10".
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 = []
html_tables = soup.find_all('table')
if html_tables:
tsv_lines.append("# --- HTML Table Data ---")
for i, table in enumerate(html_tables):
if len(html_tables) > 1:
tsv_lines.append(f"# --- Data from Table {i+1} ---")
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)
tsv_lines.append('\t'.join(row_data))
tsv_lines.append("")
else:
print("No <table> elements found.", file=sys.stderr)
rects = soup.find_all('rect')
rects_minus_35 = []
rects_minus_10 = []
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)
if rects_minus_35 or rects_minus_10:
tsv_lines.append("# --- Rectangles Data ---")
if rects_minus_35:
tsv_lines.append("# Rectangles with text '-35'")
tsv_lines.append("width\tx")
for rect in rects_minus_35:
tsv_lines.append(f"{rect['width']}\t{rect['x']}")
tsv_lines.append("")
if rects_minus_10:
tsv_lines.append("# Rectangles with text '-10'")
tsv_lines.append("width\tx")
for rect in rects_minus_10:
tsv_lines.append(f"{rect['width']}\t{rect['x']}")
tsv_lines.append("")
if not tsv_lines:
print("No data (neither tables nor rects) 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)
What changed:
- Removed the separate section for rects.
- After processing tables, the rect data for "-35" and "-10" is appended directly to the same
tsv_lines list.
- Added headers to clearly separate rect data from table data.
- Added blank lines after each rect section for readability.
This way, the output TSV file will contain all the table data first, then the rect data grouped by their text labels.