热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

检测Python中XML标记的错误嵌套-DetectingincorrectnestingofXMLtagsinPython

AquestionabouttestingpropernestingofXMLtags:关于测试XML标记的正确嵌套的问题:Igotalistoftags,extra

A question about testing proper nesting of XML tags:

关于测试XML标记的正确嵌套的问题:

I got a list of tags, extracted from top to bottom from an xml file:

我得到了一个标签列表,从xml文件中从上到下提取:

  1. Closing tags are clearly indicated by forward slash
  2. 正斜杠清楚地表示关闭标签

  3. /to and /lastname tags are incorrectly nested. They should be switched. /lastname should be within to, /to parent tags.
  4. / to和/ lastname标记嵌套不正确。他们应该切换。 / lastname应位于to,/ to parent标签内。

tag_list = ['note', 'to', 'firstname', '/firstname', 'lastname', '/to', '/lastname', '/note']

tag_list = ['note','to','firstname','/ firstname','lastname','/ to','/ lastname','/ note']

What would be the code or direction to spot that /lastname tag is outside of its parent which is to, /to pair?

发现/ lastname标记在其父级之外的代码或方向是什么?

Cheers.

2 个解决方案

#1


Make an empty stack.

做一个空堆栈。

  • Iterating through the list:
    • if you find a start tag, push it onto the stack.
    • 如果找到开始标记,则将其推入堆栈。

    • if you find an end tag, compare it to the entry on top of the stack.
      • if the stack is empty or the top doesn't match, fail.
      • 如果堆栈为空或顶部不匹配,则失败。

      • if it matches, pop the stack and continue.
      • 如果匹配,则弹出堆栈并继续。

    • 如果找到结束标记,请将其与堆栈顶部的条目进行比较。如果堆栈为空或顶部不匹配,则失败。如果匹配,则弹出堆栈并继续。

  • 遍历列表:如果找到开始标记,则将其推入堆栈。如果找到结束标记,请将其与堆栈顶部的条目进行比较。如果堆栈为空或顶部不匹配,则失败。如果匹配,则弹出堆栈并继续。

  • At the end of the iteration:
    • if the stack is empty, declare success.
    • 如果堆栈为空,则声明成功。

    • otherwise fail.
  • 在迭代结束时:如果堆栈为空,则声明成功。否则失败。

#2


Remove the backslashes, iterate on the reversed version, and compare with the original.

删除反斜杠,迭代反转版本,并与原始版本进行比较。

E.g., this will give you the indices of discrepancy:

例如,这将为您提供差异指数:

wo = [tag[1: ] if tag and tag[0] == '/' else tag for tag in taglist]
rev = list(reversed(wo))
discrepancies = [i for i in xrange(len(wo)) if wo[i] != rev[i]]

推荐阅读
author-avatar
好宝贝蛋_282
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有