如何比较两个列表并确定它们是否具有共同的字符串元素?

How to compare two lists and determine if they have common string elements?

我有域列表:

domains_1 = ['google.com', 'payments-amazon.com']
domains_2 = ['https://static-eu.payments-amazon.com/OffAmazonPayments/de/lpa/js/Widgets.js']

在这种情况下,payments-amazon.com 是公共域。鉴于域名可以很长且唯一,我将如何找到它?

我试过了,但这只有在域准确的情况下才有效。如果它们在 list/string:

中包含部分域,我需要它们匹配
matches = (set(domains_1).intersection(domains_2))
print(matches)

您可以使用像 tldextract 这样的包 - 除了在 AWS lambda 设置中,它工作得很好。或者您可以使用类似这样的方法从您的 URL.

获取域
def extract_domain(url):
    from urllib.parse import urlparse
    parsed_domain = urlparse(url)
    domain = parsed_domain.netloc or parsed_domain.path # Just in case, for urls without scheme
    domain_parts = domain.split('.')
    if len(domain_parts) > 2:
        return '.'.join(domain_parts[-(2 if domain_parts[-1] in {
            'com', 'net', 'org', 'io', 'ly', 'me', 'sh', 'fm', 'us'} else 3):])
    return domain

for x in domains_2:
    dom = extract_domain(x)
    if dom in domains_1:
        do your thing