簡體   English   中英

檢查字符串中是否包含多個子字符串 - Python

[英]checking if any of multiple substrings is contained in a string - Python

我有一個包含禁止子字符串的黑名單:我需要創建一個 if 語句來檢查給定 url 中是否包含任何被禁止的子字符串。 如果它不包含其中任何一個,我希望它執行 A(如果存在任何被禁止的內容,則只執行一次,而不是針對每個被禁止的子字符串)。 如果 url 包含一個被禁止的子字符串,我希望它做 B。

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 已禁止 substring 內部,而 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")      

有人知道更有效的方法嗎?

這是一個可能的單行解決方案:

print('there is a banned substring inside'
      if any(banned_str in url for banned_str in black_list)
      else 'no banned substrings inside')

如果您更喜歡不那么 Pythonic 的方法:

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')

您應該根據執行AB添加一個標志。

ban_flag = False
for banned in black_list:
    if banned not in url:
        continue
    else:
        ban_flag = True
if ban_flag:
    print("there is a banned substring inside")
else:
    print("no banned substrings inside")

代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM