python - 使用字典截取列表中的部分字符串
问题描述
我有一长串使用 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)
现在,该程序在运行时没有抛出任何错误。但它也根本没有按照我的要求做。它只是返回上面显示的大量结果,其中没有任何内容被删除或替换。
很困惑,虽然我确信答案就在我面前。
感谢所有帮助,在任何地方都找不到像这样的问题。
解决方案
为什么不通过将字符串拆分为字符串列表来获取您感兴趣的每个 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 始终按照您显示的方式构建,那应该可以工作。
推荐阅读
- reactjs - componentDidMount 中的笑话酶测试方法失败但控制台显示它正在工作
- php - 导航菜单 - 在产品类别和数量之间添加空间
- jquery - 使用 slideToggle 滚动到选项卡部分的顶部无法单击
- web2py - 如何更改登录页面的 response.menu?
- angular - 角度上传文件形成 3 个输入?
- node.js - Nexmo 不在 node.js 中发送短信
- python - 加快 Python .loc 函数搜索
- c# - 配置 ASP.NET 托管处理程序以处理所有请求
- r - 将字符串转换为 POSIX 对象时遇到奇怪的问题
- javascript - 如何防止用户手动访问 url,要求他们点击链接才能到达