【问题标题】:Conditional with an arbitrary number of conditions具有任意数量条件的条件
【发布时间】:2016-12-21 14:44:25
【问题描述】:

我想知道我应该如何实现这个: 我希望打印出包含列表(“关键字”列表)中包含的子字符串的字符串。但是,我将如何写出条件以检查包含列表中 every 单词的字符串?该列表具有任意数量的关键字。

在这种情况下,我的关键字和 xml 文件是从配置文件中提取的。 xml 文件是this。对于每个“URL”标签,我只打印“loc”标签中与我的关键字匹配的字符串。

from bs4 import BeautifulSoup
import urllib.request
from config import user_config
import re

# BeautifulSoup - Links and Variants

print("Starting Scrape...")

selected_size = user_config.size
url = user_config.url
req = urllib.request.urlopen(url)
keywords = user_config.keywords

soup = BeautifulSoup(req, 'xml')

soup.prettify()

inventory_url = []


for item in soup.find_all('url'):
    inventory_url.append(item.find('loc').text)

print(inventory_url)

for item in inventory_url:
    if keywords[0] in item and keywords[1] in item:
        print(item)

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    您可以使用内置的all 检查keywords 列表中的所有 元素/子字符串是否包含在当前item 中:

    for item in inventory_url:
        if all(kw in item for kw in keywords):
            print(item) 
    

    【讨论】:

      猜你喜欢
      • 2022-01-14
      • 1970-01-01
      • 2022-07-21
      • 2017-12-25
      • 1970-01-01
      • 2020-04-16
      • 2016-10-27
      • 2014-08-01
      • 1970-01-01
      相关资源
      最近更新 更多