XML标记计数器

问题描述 投票:-1回答:1

请查看附件。我是python的新手(和一般的编程;做职业转换; tldr:我在这是一个菜鸟)。

我不知道我能写什么函数会返回列表中xml标签的数量。请帮忙。 attached image

python xml python-3.x counting
1个回答
1
投票

如问题所述:

您可以检查字符串是否为XML标记,如果它以<开头并以>结尾

您需要迭代列表中的每个字符串,并使用str.startswith()str.endswith()检查第一个和最后一个字符:

In [1]: l = ["<string1>", "somethingelse", "</string1>"]

In [2]: [item for item in l if item.startswith("<") and item.endswith(">")]
Out[2]: ['<string1>', '</string1>']

这里我们只是在list comprehension中过滤了所需的字符串,但为了计算我们有多少匹配,我们可以使用sum()每次匹配时添加1

In [3]: sum(1 for item in l if item.startswith("<") and item.endswith(">"))
Out[3]: 2

这只是一种方法,我不知道你的课程有多远。一个更天真,更直接的答案版本可能是:

def tag_count(l):
    count = 0
    for item in l:
        if item.startswith("<") and item.endswith(">"):
            count += 1
    return count
© www.soinside.com 2019 - 2024. All rights reserved.