final
This commit is contained in:
110
main.py
110
main.py
@@ -1,83 +1,43 @@
|
||||
import tkinter as tk
|
||||
from tkinter import filedialog
|
||||
import algam
|
||||
import glob
|
||||
import os
|
||||
import xml.etree.ElementTree as ET
|
||||
import pandas as pd
|
||||
from pathlib import Path
|
||||
|
||||
# === 🔧 НАСТРОЙКИ (меняйте под себя) ===
|
||||
FOLDER_WITH_XMLS = r"C:\Users\jze9\Documents\work\git\kadastr12\test" # Папка с XML-файлами
|
||||
OUTPUT_XLSX_FILE = r"C:\Users\jze9\Documents\work\git\kadastr12\result.xlsx" # Куда сохранить результат
|
||||
def Pars():
|
||||
def get_all_xml_files(directory):
|
||||
"""Возвращает список полных путей ко всем .xml файлам в директории"""
|
||||
return glob.glob(os.path.join(os.path.abspath(directory), "*.xml"))
|
||||
algam.Parser(dir_xml=get_all_xml_files(xml_entry.get()),save_dir=directory_entry.get())
|
||||
|
||||
# === ⛏ ВСПОМОГАТЕЛЬНЫЕ ФУНКЦИИ ===
|
||||
def extract_text(elem, tag):
|
||||
node = elem.find(f".//{tag}")
|
||||
return node.text.strip() if node is not None and node.text else ""
|
||||
root = tk.Tk()
|
||||
root.title("Parser12")
|
||||
font = ("Arial", 12)
|
||||
root.configure(bg="#B85C38")
|
||||
options = [""]
|
||||
|
||||
def has_spatial(elem):
|
||||
return elem.find(".//SpatialElement") is not None
|
||||
#путь для сохранения файлов
|
||||
def open_directory(event, entry):
|
||||
directory_path = filedialog.askdirectory()
|
||||
entry.delete(0, tk.END)
|
||||
entry.insert(0, directory_path)
|
||||
|
||||
def collect_explanations(elem):
|
||||
return " ".join(e.text.strip() for e in elem.findall(".//Explanation") if e.text and e.text.strip())
|
||||
|
||||
# первое поле с списком
|
||||
xml_label = tk.Label(root, text="директория xml", font=font)
|
||||
xml_label.pack(anchor="w")
|
||||
xml_entry = tk.Entry(root, font=font, width=70)
|
||||
xml_entry.pack(anchor="w")
|
||||
xml_entry.bind("<Button-1>", lambda event: open_directory(event, xml_entry))
|
||||
|
||||
def process_section(tree, tag, label, records, is_zemel=True):
|
||||
section = tree.find(f".//{tag}")
|
||||
if section is None:
|
||||
return
|
||||
subtag = next(iter(section), None)
|
||||
if subtag is None:
|
||||
return
|
||||
for item in section.findall(f".//{subtag.tag}"):
|
||||
rec = {
|
||||
"Раздел КПТР": label,
|
||||
"Кадастровый номер": extract_text(item, "CadastralNumber"),
|
||||
"Кадастровый квартал": extract_text(item, "CadastralBlock"),
|
||||
"Вид объекта": extract_text(item, "ObjectType"),
|
||||
"Площадь ЗУ": extract_text(item.find("Area") or item, "Area") if is_zemel else "",
|
||||
"Погрешность определения площади": extract_text(item.find("Area") or item, "Inaccuracy") if is_zemel else "",
|
||||
"наличие координат": "да" if has_spatial(item) else "нет",
|
||||
"Пояснения": collect_explanations(item),
|
||||
}
|
||||
records.append(rec)
|
||||
directory_label = tk.Label(root, text="Выберите директорию для сохранения:", font=font)
|
||||
directory_label.pack(anchor="w")
|
||||
directory_entry = tk.Entry(root, font=font, width=70)
|
||||
directory_entry.pack(anchor="w")
|
||||
directory_entry.bind("<Button-1>", lambda event: open_directory(event, directory_entry))
|
||||
|
||||
# === 🚀 ОСНОВНОЙ КОД ===
|
||||
def main():
|
||||
records = []
|
||||
for file in os.listdir(FOLDER_WITH_XMLS):
|
||||
if not file.lower().endswith(".xml"):
|
||||
continue
|
||||
xml_path = os.path.join(FOLDER_WITH_XMLS, file)
|
||||
try:
|
||||
tree = ET.parse(xml_path)
|
||||
except ET.ParseError as e:
|
||||
print(f"❌ Ошибка в файле {file}: {e}")
|
||||
continue
|
||||
# кнопка
|
||||
empty_button = tk.Button(root, text="->", command=Pars, font=font)
|
||||
empty_button.pack(side="right", padx=10, pady=10)
|
||||
|
||||
root = tree.getroot()
|
||||
process_section(root, "FormParcels", "Образование ЗУ", records)
|
||||
process_section(root, "SpecifyParcels", "Уточнение ЗУ", records)
|
||||
process_section(root, "CadastralErrorsParcels", "Исправление ЗУ", records)
|
||||
process_section(root, "ExistNewObjectsRealty", "Уточнение ОКС", records, is_zemel=False)
|
||||
process_section(root, "CadastralErrorsOKS", "Исправление ОКС", records, is_zemel=False)
|
||||
|
||||
if not records:
|
||||
print("⚠️ Нет данных для экспорта.")
|
||||
return
|
||||
|
||||
for i, rec in enumerate(records, 1):
|
||||
rec["№ п/п"] = i
|
||||
|
||||
df = pd.DataFrame(records, columns=[
|
||||
"№ п/п",
|
||||
"Раздел КПТР",
|
||||
"Кадастровый номер",
|
||||
"Кадастровый квартал",
|
||||
"Вид объекта",
|
||||
"Площадь ЗУ",
|
||||
"Погрешность определения площади",
|
||||
"наличие координат",
|
||||
"Пояснения",
|
||||
])
|
||||
df.to_excel(OUTPUT_XLSX_FILE, index=False)
|
||||
print(f"✔️ Файл успешно сохранён: {OUTPUT_XLSX_FILE}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
root.mainloop()
|
||||
Reference in New Issue
Block a user