【发布时间】:2017-12-18 23:30:20
【问题描述】:
我正在为 linux 目录构建一个爬虫/爬虫。本质上,该程序将获取用户输入的文件类型以进行抓取 (这就是我的问题所在)
我将可接受的文件扩展名类型存储在带有嵌套列表的字典中,例如:
file_types = {'images': ['png', 'jpg', 'jpeg', 'gif', 'bmp'], 'text': ['txt', 'doc', 'pdf']}
为了让用户可以选择哪些选项,我使用了这个 for 循环:
for k, v in file_types.items():
print(k, v)
以这种格式打印字典:
audio ['mp3', 'mpa', 'wpi', 'wav', 'wpi']
text ['txt', 'doc', 'pdf']
video ['mp4', 'avi', '3g2', '3gp', 'mkv', 'm4v', 'mov', 'mpg', 'wmv', 'flv']
images ['png', 'jpg', 'jpeg', 'gif', 'bmp']
现在如果我这样做:
scrape_for = input("Please enter either the type of file, or the
extension you would like to scrape for: \n")
如何验证用户输入是否存在于我的字典 file_types 中作为键或值(我说键或值,因此如果用户输入“图像”,我可以使用键图像的值)
【问题讨论】:
-
一种不那么 Python 的方法:
key if key in file_types else reduce(lambda p,n: p or n if key in n else False, file_types.values(), False)
标签: python python-3.x dictionary