将网站上的数据转换为字典

convert data from website to a dictionary


问题

数据由bs4刮取(也要去掉白色空间)

{
            MaxRange        =       1.2,
            WeaponSprite    =       FireAxe,
            MinAngle        =       0.72,
            Type    =       Weapon,
            MinimumSwingTime        =       3.0,
            KnockBackOnNoDeath      =       TRUE,
            SwingAmountBeforeImpact =       0.002,
            Categories      =       Axe,
            ConditionLowerChanceOneIn       =       22,
            Weight  =       3,
    }

main.py

def get_info(html, obj_len):
    soup = BeautifulSoup(html, 'html.parser')
    stats = soup.find('pre')
    return stats.get_text(strip=True)[5+obj_len:]

URL = 'https://pzwiki.net/wiki/'
obj = 'Axe'
run = True

if run:
    req = requests.get(URL + obj)
    data = get_info(req.text, len(obj))

我想做什么

parsed_result = {
    'MaxRange': 1.2,
    'WeaponSprite': 'FireAxe',
    'MinAngle': 0.72,
    'Type': 'Weapon',
    'MinimumSwingTime': 3.0,
    'KnockBackOnNoDeath': 'TRUE',
    'SwingAmountBeforeImpact': 0.002,
    'Categories': 'Axe',
    'ConditionLowerChanceOneIn': 22,
    'Weight': 3,
}

基本上我想把这个类似于字典的数据转换为真正的字典,但不知道如何有效地把'='替换为':'并去掉白字,希望得到任何帮助!

答案1

使用 builtin 模块 configparse

import configparser

target = """{
            MaxRange        =       1.2,
            WeaponSprite    =       FireAxe,
            MinAngle        =       0.72,
            Type    =       Weapon,
            MinimumSwingTime        =       3.0,
            KnockBackOnNoDeath      =       TRUE,
            SwingAmountBeforeImpact =       0.002,
            Categories      =       Axe,
            ConditionLowerChanceOneIn       =       22,
            Weight  =       3
       }"""

# parse target by removing '{' & '}' and adding help `section` "[root]"
parsed = configparser.ConfigParser()

# you may need to change the corresponding method
parsed.read_string('[root]\n' + target.replace('{','').replace('}',''))

parsed_result = { **parsed['root'] }

## additional codes for taking care of numbers..
#blabla
相同问题还可以参考: convert data from website to a dictionary