将文件名放在标签之间[[

问题描述 投票:0回答:1
[OCR将几千个TIFF图像转换为ALTO XML之后,我发现xml中的文件名标记为空。

<sourceImageInformation> <fileName> </fileName> </sourceImageInformation>

我想(递归)处理所有xml文件,并在标签之间添加tiff名称。 xml的基本名称与tiff相同。最好的方法是什么?我应该将bash与find和sed一起使用,还是将Python与string.replace一起使用,还是有更好的选择?
python xml sed tags filenames
1个回答
3
投票
不要

not使用字符串处理工具来处理XML! XML不是常规格式,使用str.replace()sed或任何此类工具可能会导致误报和错误。

使用XML解析器; Python具有xml.etree.ElementTree,它使此任务足够简单:

xml.etree.ElementTree

上面处理给定目录中的所有XML文件(使用from pathlib import Path
from xml.etree import ElementTree as ET

for xmlfile in Path("directory_with_xml_files").glob("*.xml"):
    tree = ET.parse(xmlfile)
    namespace = tree.getroot().tag.partition('}')[0][1:]
    elem = tree.find(f".//{{{namespace}}}fileName")
    elem.text = f"{xmlfile.stem}.tiff"
    tree.write(xmlfile, encoding="UTF-8", xml_declaration=True)
,使用pathlib module查找XML文件)。对于每个文件,它将XML数据解析为XML树,并使用该元素的简单pathlibPath.glob() method(使用Path.glob(),这是该元素的基本名称)在树中找到第一个<fileName>元素XPath expression扩展名)并将XML树写回到原始文件。

您说过您使用了updates the text,它使用filename stem来区分版本;以上应该从根元素中选择要使用的正确名称空间。

演示:

.xml

© www.soinside.com 2019 - 2024. All rights reserved.