开发者社区> 问答> 正文

嵌入嵌套列表的过滤字典

我希望通过“ abv”值(仅使用范围的下限)来过滤以下内容。例如,如果“ ABV:4.5-5.5%”,我将使用4.5作为ABV的值)和“ cuisine” 。到目前为止,这是我的代码:

import requests
from bs4 import BeautifulSoup 
import pandas as pd
import csv
from html.parser import HTMLParser


r = requests.get("https://www.webstaurantstore.com/article/27/different-types-of- 
beers.html")
soup = BeautifulSoup(r.text, "html.parser")
beer_titles = soup.find_all('h3')[3:-1]
beer_titles_list = []
for b in beer_titles:
    result = b.text.strip()
    beer_titles_list.append(result)

helpme = soup.find_all('p')
def __init__(self):
    helpme().__init__()
    helpme.reset()
    helpme.fed = []
helpme_clean = []
for d in helpme:
    result = d.text.strip()
    helpme_clean.append(result)
attributes = helpme_clean[36:-20]


helpme_clean = []
for d in helpme:
    result = d.text.strip()
    helpme_clean.append(result)
attributes = helpme_clean[36:-20]
attributes
attributes = attributes[:252]
del attributes[231]
del attributes[205]
del attributes[204]
del attributes[203]
del attributes[200]
del attributes[191]
del attributes[170]
del attributes[169]
del attributes[168]
del attributes[144]
del attributes[126]
del attributes[125]
del attributes[124]
del attributes[118]
del attributes[107]
del attributes[81]
del attributes[80]
del attributes[79]
del attributes[68]
del attributes[67]
del attributes[66]
del attributes[45]
del attributes[44]
del attributes[43]
del attributes[22]
del attributes[21]
del attributes[20]

n = 5
main_list = [attributes[i:i+n] for i in range(0, len(attributes), n)]
main_dict = dict(zip(beer_titles_list, main_list))
main_dict

目标是接受用户输入(ABV%偏好和菜肴搭配)并找到有关啤酒样式的建议。我正在尝试建立一个过滤器系统,使其仅返回与ABV%偏好和料理配对均匹配的啤酒。任何提示将非常感谢。

提前非常感谢大家!

问题来源:stackoverflow

展开
收起
is大龙 2020-03-23 17:15:58 479 0
1 条回答
写回答
取消 提交回答
  • 匹配“ ABV:4.5-5.5%”的“ 4.5”最直接的想法是使用正则表达式。这是代码:

    import re
    string='ABV: 4.5-5.5%'
    output=re.search(r'([\d\.]+)\-[\d\.]+',string)[1]
    

    至于删除列表中的乘法值,使用列表理解是一种简单的方法:

    new_list=[old_list[i] for i in range(len(old_list)) if not i in indices]
    

    例如:

    import numpy as np 
    old_list=np.random.random(10)
    indices=np.random.choice(np.arange(0,10),5)
    new_list=[old_list[i] for i in range(len(old_list)) if not i in indices]
    
    print('The original list is:',list(old_list))
    print('The indices to be removed are:',list(indices))
    print('The new list is:',list(new_list))
    

    输出:

    原始列表为:[0.9233779986812494、0.47976112127600334、0.2669764806705126、0.8598525413490794、0.03257522197544993、0.472960144751734、0.07720026239677213、0.22969097769323488、0.3039956214047107、0.5079366193702746]

    要删除的索引是:[2,0,1,7,3]

    新列表为:[0.03257522197544993、0.472960144751734、0.07720026239677213、0.3039956214047107、0.5079366193702746]

    回答来源:stackoverflow

    2020-03-23 17:16:06
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
继承与功能组合 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载