-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscratch_15.py
More file actions
56 lines (46 loc) · 2.2 KB
/
Copy pathscratch_15.py
File metadata and controls
56 lines (46 loc) · 2.2 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
import os
import xml.etree.ElementTree as ET
def extract_and_mark_xml(input_dir, output_txt_path, output_dir):
# 创建输出目录如果它不存在
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# 创建一个列表来保存所有提取的文本
extracted_texts = []
text_index = 1
# 遍历指定路径及其子路径中的所有文件
for root, _, files in os.walk(input_dir):
for file in files:
if file.endswith('.xml'):
file_path = os.path.join(root, file)
output_file_path = os.path.join(output_dir, os.path.relpath(file_path, input_dir))
# 解析XML文件
tree = ET.parse(file_path)
root_element = tree.getroot()
modified = False
# 提取<label>和<description>标签内容
for element in root_element.iter():
if element.tag in ['label', 'description']:
# 保存原文到列表中
print(element.text)
extracted_texts.append(element.text)
# 用索引标记原文位置
element.text = str(text_index)
text_index += 1
modified = True
# 如果文件被修改,保存修改后的XML
if modified:
print(output_file_path)
if not os.path.exists(output_file_path):
os.system(f"touch {output_file_path}")
with open(output_file_path, 'wb') as f: # 使用 'wb' 模式写入二进制文件
tree.write(f, encoding='utf-8', xml_declaration=True)
# 将提取的文本写入TXT文件
with open(output_txt_path, 'w', encoding='utf-8') as f:
for text in extracted_texts:
f.write(text + '\n')
# 指定输入目录、输出TXT文件路径和输出目录
input_directory = r'D:\steam\steamapps\workshop\content\294100\1802857253\Defs'
output_txt_file = r'translations.txt'
output_dir = r'.\outputs'
# 调用函数执行提取和标记操作
extract_and_mark_xml(input_directory, output_txt_file, output_dir)