首页 > 解决方案 > 使用字典截取列表中的部分字符串

问题描述

我有一长串使用 Python 3 中的 Beautiful Soup 生成的列表。

现在,列表是这样生成的..

mylist = [a['href'] for a in soup.find_all('a', href=True) if a.text] 

这是一个网络抓取的东西,但只知道它返回一个列表。

并以列表的形式返回如下结果:

'目录/类别/书籍/travel_2/index.html',

'目录/类别/书籍/mystery_3/index.html',

'目录/类别/书籍/历史小说_4/index.html'

在我打印我的清单之前,我想删除各种无用的信息(例如“目录/”、“类别/”和“书籍/”,以便只显示重要信息(旅行、神秘或历史小说)。

我能够使用以下方法成功替换一件事:

mylist = [item.replace("catalogue/category/", "") for item in mylist]

效果很好。但我不相信 .replace 会接受超过 2 个参数,这使我无法从结果中删除其他内容,例如 "index.html" 。我宁愿不要为我想要替换的所有内容写那行。这就是为什么我试图使用字典中的键和值作为 .replace() 参数:

replacedict = {"catalogue/category/": "" , "index.html": ""}

mylist = [a['href'] for a in soup.find_all('a', href=True) if a.text]

def replace_all(mylist, replacedict):
     for k, v in replacedict.items():
         mylist = [item.replace(k, v) for item in mylist]
     return mylist

replace_all(mylist, replacedict)

print(mylist)

现在,该程序在运行时没有抛出任何错误。但它也根本没有按照我的要求做。它只是返回上面显示的大量结果,其中没有任何内容被删除或替换。

很困惑,虽然我确信答案就在我面前。

感谢所有帮助,在任何地方都找不到像这样的问题。

标签: pythonlistfunctiondictionaryreplace

解决方案


为什么不通过将字符串拆分为字符串列表来获取您感兴趣的每个 URL 的部分。例如:

$ python
Python 3.7.2 (default, Dec 27 2018, 07:35:06) 
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> string_list = ['catalogue/category/books/travel_2/index.html', 'catalogue/category/books/mystery_3/index.html', 'catalogue/category/books/historical-fiction_4/index.html']
>>> array_list = [s.split('/') for s in string_list]
>>> array_list
[['catalogue', 'category', 'books', 'travel_2', 'index.html'], ['catalogue', 'category', 'books', 'mystery_3', 'index.html'], ['catalogue', 'category', 'books', 'historical-fiction_4', 'index.html']]
>>> [a[3] for a in array_list]
['travel_2', 'mystery_3', 'historical-fiction_4']

如果 URL 始终按照您显示的方式构建,那应该可以工作。


推荐阅读