我有一个代码片段,添加到计数器,如果条件为真.我怎么缩短它?



我正在从维基百科页面提取所有外部链接,并以这种方式计算它们:

count = 0 
for a in soup.find_all('a', href=True):
    try:
        
        if "wikilink" in a["rel"][0].lower():
            count = count + 1
        
    except:
        pass
print(count)

我只是创建了一个count变量,并获得所有的a标签,如果条件为真,它只是加起来。我如何使这段代码以python的方式简洁?

可以使用sum()函数

links = soup.select('a[href][rel]')
count = sum("wikilink" in a["rel"][0].lower() for a in links))

选择器将只返回具有rel属性的锚,因此您不应该需要try/except来跳过那些没有的锚。

我不知道这是否会被认为更python化,但是您可以使用sum

中的生成器表达式执行此计数。
count = sum(1 for a in soup.find_all('a', href=True) if "wikilink" in a.get("rel", [''])[0].lower())

我可能会这样写:

print(sum(
    "wikilink" in a.get("rel", "null")[0].lower()
    for a in soup.find_all('a', href=True)
))

在这里使用"null"作为一个虚拟值,允许[0].lower()在不提高和不增加总和的情况下运行(我假设a.get("rel")不可能返回像int那样不可索引的东西)。

这样会更python化,但是这个长表达式变得不那么可读:

sum(1 for a in soup.find_all('a', href=True) if isinstance(a.get("rel"), list) and len(a.get("rel")) > 0 and "wikilink" in a.get("rel")[0].lower())

检查isinstance(a.get("rel"), list) and len(a.get("rel")) > 0确保不会有异常,所以你不必在try/except中包装它。

为了提高可读性,我将它分成两行:
check = lambda a: isinstance(a.get("rel"), list) and len(a.get("rel")) > 0 and "wikilink" in a.get("rel")[0].lower()
count = sum(1 for a in soup.find_all('a', href=True) if check(a))

相关内容

最新更新