如何过滤URL的嵌套列表?

2024-09-25 10:18:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试根据URL中的单词筛选URL的列表。在

例如,如果URL的任何部分包含/thema/或{},则应该删除它。在

样品清单:

p = [['www.sample.de/fl/autor/xxx',
      'www.sample.de/fl/autor/xxx',
      'www.sample.de/fl/autor/xxx',],
      ['www.temp.de/thema/xxx',
      'www.temp.de/thema/xxx',]
    ]

我的代码:

^{pr2}$

但是,这不会过滤任何内容。在

如何正确地执行此操作?在


Tags: sample代码url内容列表www样品de
3条回答

您应该使用标志来执行此操作:

p = ['www.sample.de/fl/autor/xxx',
      'www.sample.de/fl/autor/xxx',
      'www.sample.de/fl/autor/xxx',
      'www.temp.de/thema/xxx',
      'www.temp.de/thema/xxx',
     'www.sample.de/fl/autoor/xxx',
     'www.temp.de/theema/xxx',
    ]

filters = ['/autor/', '/thema/' ]

fil = []
for sbl in p:
    flag = False
    for i in filters:
        if i in sbl:
            flag = True
    if not flag:
        fil.append(sbl)
fil
#['www.sample.de/fl/autoor/xxx', 'www.temp.de/theema/xxx']

如果在列表理解中找到任何筛选器,则可以通过删除url在其中使用any()

from itertools import chain

p = [['www.sample.de/fl/autor/xxx',
      'www.sample.de/fl/autor/xxx',
      'www.sample.de/fl/autor/xxx',],
      ['www.temp.de/thema/xxx',
      'www.temp.de/thema/xxx',]
    ]

filters = ['/autor/', '/thema/' ]  
p = [x for x in chain.from_iterable(p) if not any(f in x for f in filters)]

# []

使用正则表达式。在

例如:

import re


p = ['www.sample.de/fl/autor/xxx',
      'www.sample.de/fl/autor/xxx',
      'www.sample.de/fl/autor/xxx',
      'www.temp.de/thema/xxx',
      'www.temp.de/thema/xxx',
    ]

filters = ['/autor/', '/thema/' ]
pattern = re.compile(r"(\b" + "|".join(filters) + r"\b)")
print([i for i in p if not pattern.search(i)])

按注释编辑

^{pr2}$

相关问题 更多 >