-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
230 lines (181 loc) · 7.56 KB
/
main.py
File metadata and controls
230 lines (181 loc) · 7.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import zipfile
import xml.dom.minidom
from pathlib import Path
import pyperclip # pip install pyperclip
def copy_table_to_clipboard(odt_path):
tables = extract_tables_with_metadata(odt_path)
if not tables:
print("❌ Keine Tabelle gefunden.")
return
table = tables[0] # oder die gewünschte auswählen
lines = []
for row in table['rows']:
# Zelleninhalt: \n → Leerzeichen
cells = [cell['content'].replace('\n', '').strip() for cell in row['cells']]
# CSV: Anführungszeichen, falls Komma oder Zeilenumbrüche drin sind
line = '\t'.join(f'"{c}"' if '\t' in c or '\n' in c or '"' in c else c for c in cells)
lines.append(line)
csv_text = '\n'.join(lines)
pyperclip.copy(csv_text)
print("✅ Tabelle (Tab-getrennt) in Zwischenablage kopiert – ohne Zeilenumbrüche.")
def analyze_odt_structure(filepath):
"""
Analysiert die Struktur eines ODT-Dokuments
Args:
filepath (str): Pfad zur ODT-Datei
Returns:
dict: Dokumentstruktur-Informationen
"""
# ODT-Datei öffnen (ist eine ZIP-Datei)
with zipfile.ZipFile(filepath, 'r') as zip_ref:
# content.xml extrahieren
content_xml = zip_ref.read('content.xml').decode('utf-8')
# XML parsen
dom = xml.dom.minidom.parseString(content_xml)
# Strukturinformationen sammeln
structure = {
'tables': [],
'paragraphs': [],
'headings': []
}
# Tabellen extrahieren
tables = dom.getElementsByTagName('table:table')
for i, table in enumerate(tables):
table_info = {
'table_id': i,
'name': table.getAttribute('table:name'),
'rows': []
}
# Zeilen und Zellen extrahieren
rows = table.getElementsByTagName('table:table-row')
for row in rows:
row_data = []
cells = row.getElementsByTagName('table:table-cell')
for cell in cells:
# Text aus string-value Attribut extrahieren
text = cell.getAttribute('office:string-value')
row_data.append(text)
table_info['rows'].append(row_data)
structure['tables'].append(table_info)
return structure
def extract_tables_with_metadata(odt_path):
"""
Extrahiert Tabellen mit zusätzlichen Metadaten
"""
def get_cell_text(cell_node):
def text_from_node(node):
"""Rekursiv Text extrahieren, auch mit <text:line-break/>"""
texts = []
for child in node.childNodes:
if child.nodeType == child.TEXT_NODE:
texts.append(child.nodeValue)
elif child.nodeType == child.ELEMENT_NODE:
if child.tagName == "text:line-break":
texts.append("\n")
else:
texts.append(text_from_node(child))
return "".join(texts)
# 1. Versuch: <text:p> Nodes
text_p_nodes = cell_node.getElementsByTagName("text:p")
if text_p_nodes:
paragraphs = []
for tp in text_p_nodes:
paragraphs.append(text_from_node(tp))
return "\n".join(paragraphs)
# 2. Fallback
return cell_node.getAttribute('office:string-value') or ""
with zipfile.ZipFile(odt_path, 'r') as zip_ref:
content_xml = zip_ref.read('content.xml').decode('utf-8')
dom = xml.dom.minidom.parseString(content_xml)
tables = dom.getElementsByTagName('table:table')
extracted_tables = []
for table_idx, table in enumerate(tables):
table_data = {
'table_id': table_idx,
'name': table.getAttribute('table:name') or f'Table_{table_idx}',
'dimensions': {'rows': 0, 'columns': 0},
'rows': [],
'metadata': {
'has_header': False,
'data_types': [],
'empty_cells': 0
}
}
rows = table.getElementsByTagName('table:table-row')
table_data['dimensions']['rows'] = len(rows)
max_columns = 0
for row_idx, row in enumerate(rows):
row_info = {
'row_index': row_idx,
'cells': [],
'is_header': row_idx == 0 # Erste Zeile als Header markieren
}
cells = row.getElementsByTagName('table:table-cell')
max_columns = max(max_columns, len(cells))
for cell_idx, cell in enumerate(cells):
cell_value = get_cell_text(cell)
if 'xylander' in cell_value:
print(f"DEBUG: row={row_idx}, col={cell_idx}, content={repr(cell_value)}")
cell_info = {
'row': row_idx,
'column': cell_idx,
'content': cell_value,
'is_empty': not cell_value.strip(),
'data_type': infer_data_type(cell_value)
}
if not cell_value.strip():
table_data['metadata']['empty_cells'] += 1
row_info['cells'].append(cell_info)
table_data['rows'].append(row_info)
table_data['dimensions']['columns'] = max_columns
table_data['metadata']['has_header'] = len(rows) > 1
extracted_tables.append(table_data)
return extracted_tables
def infer_data_type(value):
"""Bestimmt den Datentyp eines Wertes"""
if not value:
return 'empty'
# Numerisch prüfen
try:
float(value.replace(',', '').replace('€', '').replace('%', ''))
return 'numeric'
except:
pass
# Datum prüfen
if any(month in value.lower() for month in ['januar', 'februar', 'märz', 'april', 'mai', 'juni']):
return 'date'
return 'text'
# Beispiel: Tabellen nach Schlüsselwort filtern
def find_tables_with_keyword(odt_path, keyword):
"""Findet Tabellen, die ein bestimmtes Schlüsselwort enthalten"""
tables = extract_tables_with_metadata(odt_path)
matching_tables = []
for table in tables:
for row in table['rows']:
for cell in row['cells']:
if keyword.lower() in cell['content'].lower():
matching_tables.append(table)
break
else:
continue
break
return matching_tables
# Beispiel: Tabelle als CSV exportieren
def export_table_to_csv(table_data, output_path):
"""Exportiert eine Tabelle als CSV-Datei"""
with open(output_path, 'w', encoding='utf-8') as f:
for row in table_data['rows']:
row_values = [cell['content'] for cell in row['cells']]
f.write(','.join(f'"{value}"' for value in row_values) + '\n')
# Beispiel: Statistiken über alle Tabellen berechnen
def calculate_table_statistics(odt_path):
"""Berechnet Statistiken über alle Tabellen im Dokument"""
tables = extract_tables_with_metadata(odt_path)
stats = {
'total_tables': len(tables),
'total_rows': sum(len(table['rows']) for table in tables),
'total_cells': sum(len(row['cells']) for table in tables for row in table['rows']),
'empty_cells': sum(table['metadata']['empty_cells'] for table in tables),
'tables_with_headers': sum(1 for table in tables if table['metadata']['has_header'])
}
return stats