Итак далеко, у меня есть этот код:
Код: Выделить всё
import os
import xml.etree.ElementTree as ET
def process_xml_files(source_dir, target_dir):
# Create the target directory if it doesn't exist
if not os.path.exists(target_dir):
os.makedirs(target_dir)
# Iterate through all files in the source directory
for filename in os.listdir(source_dir):
if filename.endswith('.xml'):
file_path = os.path.join(source_dir, filename)
tree = ET.parse(file_path)
root = tree.getroot()
# Process each platformID group
for platformID in ['0', '1', '3']:
elements = root.findall(f".//namerecord[@platformID='{platformID}']")
if elements:
nameID_elements = {int(el.get('nameID')): el for el in elements}
if 8 not in nameID_elements:
# Create a new element with nameID="8"
new_element = ET.Element('namerecord', attrib={
'nameID': '8',
'platformID': platformID,
'platEncID': elements[0].get('platEncID'),
'langID': elements[0].get('langID'),
})
new_element.text = "\r" " " "New Entry" "\r" " "
# Insert the new element in the correct position
sorted_nameIDs = sorted(list(nameID_elements.keys()) + [8])
insert_index = sorted_nameIDs.index(8)
# Find the parent element
parent = root.find(".//name")
parent.insert(insert_index, new_element)
# Write the modified XML to the target directory
target_file_path = os.path.join(target_dir, filename)
tree.write(target_file_path, encoding='utf-8', xml_declaration=True)
source_directory = input("Enter the source directory: ")
target_directory = input("Enter the target directory: ")
process_ttx_files(source_directory, target_directory)
Обратите внимание, что идентификаторы платформы сгруппированы вместе и в последовательном порядке по nameID:
Код: Выделить всё
Safe
Kitten
Calico
KittenCalico:1135918450
KittenCalico
1.00
KittenCalico
Safe
Kitten
Calico
KittenCalico:1135918450
KittenCalico
1.00
KittenCalico
Safe
Kitten Calico
Vanilla
KittenCalico:1135918450
KittenCalico
1.00
KittenCalico
Код: Выделить всё
Safe
Kitten
Calico
KittenCalico:1135918450
KittenCalico
1.00
KittenCalico
New Entry
New Entry
New Entry
Safe
Kitten
Calico
KittenCalico:1135918450
KittenCalico
1.00
KittenCalico
Safe
Kitten Calico
Vanilla
KittenCalico:1135918450
KittenCalico
1.00
KittenCalico
Код: Выделить всё
Safe
Kitten
Calico
KittenCalico:1135918450
KittenCalico
1.00
KittenCalico
New Entry
Safe
Kitten
Calico
KittenCalico:1135918450
KittenCalico
1.00
KittenCalico
New Entry
Safe
Kitten Calico
Vanilla
KittenCalico:1135918450
KittenCalico
1.00
KittenCalico
New Entry
Я не знаю, как это сделать. напишите код для достижения этой цели. Любая помощь будет оценена по достоинству, спасибо!
Подробнее здесь: https://stackoverflow.com/questions/792 ... ython-code
Мобильная версия