Skip to main content
 首页 » 编程设计

python之正则表达式在 Python 3 中查找列表中的字符串

2025年05月04日29linjiqin

如何从列表中获取 base.php?id=5314?

import urllib.parse 
import urllib.request 
from bs4 import BeautifulSoup 
url = 'http://www.fansubs.ru/search.php' 
values = {'Content-Type:' : 'application/x-www-form-urlencoded', 
      'query' : 'Boku dake ga Inai Machi' } 
d = {} 
data = urllib.parse.urlencode(values) 
data = data.encode('ascii') 
req = urllib.request.Request(url, data) 
with urllib.request.urlopen(req) as response: 
   the_page = response.read() 
soup = BeautifulSoup(the_page, 'html.parser') 
for link in soup.findAll('a'): 
    d[link] = (link.get('href')) 
x = (list(d.values())) 

请您参考如下方法:

您可以使用内置函数 filter结合 regex。示例:

import re 
 
# ... your code here ... 
 
x = (list(d.values())) 
test = re.compile("base\.php\?id=", re.IGNORECASE) 
results = filter(test.search, x) 

根据评论更新:可以将过滤结果转换成列表:

print(list(results)) 

具有以下硬编码列表的示例结果:

x = ["asd/asd/asd.py", "asd/asd/base.php?id=5314", 
     "something/else/here/base.php?id=666"] 

你得到:

['asd/asd/base.php?id=5314', 'something/else/here/base.php?id=666'] 

此答案基于 this讨论过滤列表的页面。它有更多的实现来做同样的事情,可能更适合你。希望对你有帮助