首页 > 解决方案 > 你将如何在 Python 中清理这本字典?

问题描述

这是我第一次尝试构建非 Web 并涉及逻辑编码的东西。

请看下面这本可怕的字典:

  Messy_Dict=
    {
        'name': "['\\r\\n                  NASDAQ: BKEP\\r\\n          ']", 
        'underlying': "['1.12']", 
        'strike_prices_list': ["['2.50'", " '5.00'", " '7.50']"], 
        'call_bid': ["['\\r\\n0.05            '", " '\\r\\n0.00            '", " '\\r\\n0.00            ']"], 
        'put_ask': ["['\\r\\n2.10            '", " '\\r\\n4.50            '", " '\\r\\n7.00            ']"]
    }

我想要做的是清理每个字典值中不必要的子字符串以获得如下内容:

Clean_Dict=
    {
        'name': "BKEP", 
        'underlying': "1.12", 
        'strike_prices_list': ["2.50", "5.00", "7.50"], 
        'call_bid': ["0.05", "0.00", "0.00"], 
        'put_ask': ["2.10", "4.50", "7.00"]
    }

我已经设法从Messy_DictClean_Dict但我使用了非常野蛮的手段来做到这一点。我只想说它包括一个 for 循环和多个 strip()、replace(''、'') 方法。看着我的 .py 文件中的那段代码让我很痛苦。

所以我想,有没有更优雅的方法来执行将 Messy_Dict 转换为 Clean_Dict 的所需任务?我觉得我的基本面好像遗漏了一些东西。

编辑

def parse(self, response):
        strike_prices_main = response.css('.highlight , .aright .strike-col').css('::text').extract()
        if not strike_prices_main:
            pass
        else:
            name = response.css('#instrumentticker::text').extract()
            strike_prices_list = response.css('.aright .strike-col').css('::text').extract()
            call_bid = response.css('.aright td:nth-child(5)').css('::text').extract()
            put_ask = response.css('.aright td:nth-child(14)').css('::text').extract()
            underlying = response.css('.pricewrap .bgLast').css('::text').extract()
            file.write('%s|%s|%s|%s|%s\n'%(name,underlying,strike_prices_list,call_bid,put_ask))

使用蜘蛛爬行!

标签: pythondictionaryweb-scraping

解决方案


也许是这样的:

import re
Messy_Dict= \
{
    'name': "['\\r\\n                  NASDAQ: BKEP\\r\\n          ']", 
    'underlying': "['1.12']", 
    'strike_prices_list': ["['2.50'", " '5.00'", " '7.50']"], 
    'call_bid': ["['\\r\\n0.05            '", " '\\r\\n0.00            '", " '\\r\\n0.00            ']"], 
    'put_ask': ["['\\r\\n2.10            '", " '\\r\\n4.50            '", " '\\r\\n7.00            ']"]
}
regexstr = "\\\\(r|n)|\s|\[|\]|\'|NASDAQ:"

dict_clean = {}
for k, v in Messy_Dict.items():
    if isinstance(v, list):
        list_clean = []
        for el in v:            
            el_clean = re.sub(regexstr, "", el)
            list_clean.append(el_clean)
        dict_clean[k] = list_clean
    else:
        dict_clean[k] = re.sub(regexstr, "", v)
dict_clean

推荐阅读