欢迎光临
我们一直在努力

我使用 Python 自动化 XML 字段检查的那一天

我使用 python 自动化 xml 字段检查的那一天

这一切都始于我接受检查多个 xml 文件是否缺少字段的任务。在我们继续下一步之前,团队需要确保这些文件中存在所有必填字段。听起来很简单,对吧?嗯,不完全是。

我打开第一个 xml 文件,扫描属性,手动查找必填字段,然后勾选相应的框。正如你所预料的那样,很快就会感到疲倦。在一个文件中只看了几分钟后,我的眼睛变得呆滞,我没有真正的信心我没有错过一些重要的事情。我的意思是,xml 可能非常挑剔,单个缺失字段可能会导致严重问题。

我有一种令人痛苦的恐惧感,因为我知道我还有一堆文件需要处理。当然,准确性至关重要——一个被忽视的缺失字段可能会带来灾难。因此,经过几次深呼吸和思考片刻后,我决定必须有更好的方法来解决这个问题。

顿悟:自动化来救援

作为一名程序员,我有一个想法:为什么不写一个脚本来为我完成这项单调的工作呢?我可以将其自动化并保证准确性,同时在过程中保持理智,而不是手动检查每个字段。是时候利用 python 的力量了。

立即学习Python免费学习笔记(深入)”;

这个概念很简单:

  • 我将必填字段列表存储在 json 文件中,这使得脚本具有高度的可重用性和适应性。通过使用这种方法,脚本可以轻松处理其他 xml 文件,甚至是那些具有不同结构的文件。您只需使用任何新 xml 格式的所需字段更新 json 文件,即可让脚本自动调整为不同的 xml 模式而无需修改。
  • 我需要编写一个 python 脚本来遍历每个 xml 文件,检查是否缺少任何必填字段,然后输出摘要。

这样,我可以轻松识别每个文件中缺少某个字段的次数、存在多少个属性,并获得清晰的报告 – 不再需要无休止的手动检查,不再出现错误。这是我的做法。

编写实用程序脚本

首先,我需要加载必填字段的列表。这些存储在键 required_fields 下的 json 文件中,因此我编写了一个函数来读取此文件:

import os
import json
import xml.etree.elementtree as et

def load_required_fields(json_file_path):
    with open(json_file_path, 'r') as file:
        data = json.load(file)
        return data.get("required_fields", [])

然后真正的魔法来了。我编写了一个函数来解析每个 xml 文件,循环遍历其属性,并检查每个必填字段是否存在:

def check_missing_fields(file_path, required_fields):
    # load the xml file
    tree = et.parse(file_path)
    root = tree.getroot()

    # initialize variables to store counts and track missing fields
    total_properties = 0
    missing_fields_counts = {field: 0 for field in required_fields}

    # loop through each property to check for missing fields
    for property in root.findall('.//property'):
        total_properties += 1
        for field in required_fields:
            # use the find() method to look for direct children of the property element
            element = property.find(f'./{field}')
            # check if the field is completely missing (not present)
            if element is none:
                missing_fields_counts[field] += 1

    # print the results
    print('-----------------------------------------')
    print(f'file: {os.path.basename(file_path)}')
    print(f'total number of properties: {total_properties}')
    print('number of properties missing each field:')
    for field, count in missing_fields_counts.items():
        print(f'  {field}: {count} properties')
    print('-----------------------------------------')

此函数加载 xml 文件,计算属性数量,并跟踪每个必填字段缺少多少属性。该函数打印出一份报告,显示每个文件处理的结果。

最后,我将所有内容放在 main() 函数中。它将迭代指定目录中的所有 xml 文件并对每个文件运行字段检查函数:

def main():
    # directory containing xml files
    xml_dir = 'xmls'
    json_file_path = 'required_fields.json'

    # load required fields from json file
    required_fields = load_required_fields(json_file_path)

    # iterate over each file in the xmls directory
    for file_name in os.listdir(xml_dir):
        if file_name.endswith('.xml'):
            file_path = os.path.join(xml_dir, file_name)
            check_missing_fields(file_path, required_fields)

if __name__ == "__main__":
    main()

运行该过程后,您将收到与此类似的结果摘要:

File: properties.xml
Total number of properties: 4170
Number of properties missing each field:
  Title: 0 properties
  Unit_Number: 0 properties
  Type: 0 properties
  Bedrooms: 0 properties
  Bathrooms: 0 properties
  Project: 0 properties
  Price: 0 properties
  VAT: 0 properties
  Status: 10 properties
  Area: 0 properties
  Location: 100 properties
  Latitude: 30 properties
  Longitude: 0 properties
  Apartment_Floor: 0 properties
  Block: 0 properties
  Phase: 0 properties
  Construction_Stage: 0 properties
  Plot_Size: 0 properties
  Yard: 120 properties
  Description: 0 properties
  gallery: 27 properties

结果:保持理智

一切准备就绪后,我就在 xml 文件目录上运行脚本。输出正是我所需要的:一个简洁的摘要,显示每个文件中有多少属性缺少哪些字段,以及每个 xml 中的属性总数。

我无需花费数小时手动检查每个文件,而是在几秒钟内得到答案。该脚本捕获了几个丢失的字段,如果我继续手动路线,我可能会忽略这些字段。

经验教训

  1. 自动化是救星:每当您面临重复性任务时,请考虑如何将它们自动化。它不仅可以节省您的时间,还可以降低人为错误的风险。
  2. 准确性很重要:在这种情况下,准确性至关重要。像我写的这样一个简单的脚本可以确保您不会忽略任何事情,这在处理关键数据时尤其重要。
  3. 利用你的编程技能:有时,我们会陷入手动做事的困境,即使我们有能力让我们的生活更轻松。花点时间退一步问自己,“有没有更有效的方法来做到这一点?”

最终,一开始令人厌烦且容易出错的任务变成了一次有益的体验。现在,每当我接到感觉乏味或容易出错的任务时,我都会提醒自己脚本和自动化的力量。我想知道接下来我还可以简化多少其他任务……

您可以通过克隆我创建的 xml checker 存储库来快速开始这种自动化。这将为您提供所需的一切,包括脚本和示例文件。从那里,您将能够自己运行自动化,对其进行自定义以满足您的需求或进一步扩展其功能。

尽情享受!

赞(0) 打赏
未经允许不得转载:码农资源网 » 我使用 Python 自动化 XML 字段检查的那一天
分享到

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续提供更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册