检查字符串Python中是否包含多个子字符串中的任何一个子字符串
我有一个包含禁用子字符串的黑名单:我需要做一个if语句,检查给定url中是否包含任何禁用子字符串。如果它不包含它们中的任何一个,我希望它执行一次(如果存在任何被禁止的子字符串,则只执行一次,而不是针对每个被禁止的子字符串)。如果url包含一个被禁止的子字符串,我希望它执行B检查字符串Python中是否包含多个子字符串中的任何一个子字符串,python,python-3.x,for-loop,if-statement,any,Python,Python 3.x,For Loop,If Statement,Any,我有一个包含禁用子字符串的黑名单:我需要做一个if语句,检查给定url中是否包含任何禁用子字符串。如果它不包含它们中的任何一个,我希望它执行一次(如果存在任何被禁止的子字符串,则只执行一次,而不是针对每个被禁止的子字符串)。如果url包含一个被禁止的子字符串,我希望它执行B black_list = ['linkedin.com', 'yellowpages.com', 'facebook.com', 'bizapedia.com', 'manta.com', 'ye
black_list = ['linkedin.com', 'yellowpages.com', 'facebook.com', 'bizapedia.com', 'manta.com',
'yelp.com', 'nextdoor.com', 'industrynet.com', 'twitter.com', 'zoominfo.com',
'google.com', 'yellow-listings.com', 'kompass.com', 'dnb.com', 'tripadvisor.com']
这里有两个简单的URL示例,我用它们来检查它是否有效。Url1禁止了内部的子字符串,而url2没有
url1 = 'https://www.dnb.com/'
url2 = 'https://www.ok/'
我尝试了下面的代码,但不知道是否有更好的方法(计算效率更高)来实现它?我有一个100k+URL的数据帧,所以担心这会非常慢
mask = []
for banned in black_list:
if banned in url:
mask.append(True)
else:
mask.append(False)
if any(mask):
print("there is a banned substring inside")
else:
print("no banned substrings inside")
有人知道更有效的方法吗?您应该根据执行
a
或B
的不同添加一个标志
ban_标志=False
对于黑名单中被禁止的:
如果在url中未禁用:
持续
其他:
ban_flag=True
如果是班尤旗:
打印(“内部有禁止的子字符串”)
其他:
打印(“内部没有禁止的子字符串”)
代码:
black_list = ['linkedin.com', 'yellowpages.com', 'facebook.com', 'bizapedia.com', 'manta.com',
'yelp.com', 'nextdoor.com', 'industrynet.com', 'twitter.com', 'zoominfo.com',
'google.com', 'yellow-listings.com', 'kompass.com', 'dnb.com', 'tripadvisor.com']
def is_url_banned(url):
for banned in black_list:
if banned in url :
print("there is a banned substring inside")
return
print("no banned substrings inside")
is_url_banned('https://www.dnb.com/')
is_url_banned('https://www.ok/')
结果:
there is a banned substring inside
no banned substrings inside
以下是一种可能的单线解决方案:
print('there is a banned substring inside'
if any(banned_str in url for banned_str in black_list)
else 'no banned substrings inside')
如果您更喜欢不太像蟒蛇的方法:
if any(banned_str in url for banned_str in black_list):
print('there is a banned substring inside')
else:
print('no banned substrings inside')