我正在从维基百科页面提取所有外部链接,并以这种方式计算它们:
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))