gpt4 book ai didi

python - 将字符串转换为字典

转载 作者:太空宇宙 更新时间:2023-11-04 02:40:25 24 4
gpt4 key购买 nike

我有一个包含以下内容的 .js 文件:

AppSettings = {
projectName:'myproject',
url: 'https://www.google.com',
appKey: 'k2y-myproject_124439_18111',
newsKey: '',
version: moment().format('YYMMDD_HHmmss'),
mixpanelToken: '08e97bef3930f330037d9z6t56395060'
};

我想把它转换成一个我可以按如下方式访问的 python 字典

>>> print(data['AppSettings']['url']
>>> 'https://www.google.com'

实现此目标的最佳方法是什么?

最佳答案

代码

d = {'AppSettings':{}}
with open('tt.js', 'r') as f:
next(f)
for line in f:
splitLine = line.strip().replace(',','').split(':')
d['AppSettings'][splitLine[0]] = "".join(splitLine[1:])

d['AppSettings']['url']=d['AppSettings']['url'].replace('htt‌​ps//','https://')
d['AppSettings'].pop("}", None) #remove last item "}" from dict

print(d['AppSettings']['url'])
print(d['AppSettings']['newsKey'])
print(d['AppSettings']['appKey'])
print(d['AppSettings']['version'])
print(d['AppSettings']['mixpanelToken'])

示例输出

'https://www.google.com'
''
'k2y-myproject_124439_18111'
moment().format('YYMMDD_HHmmss')
'08e97bef3930f330037d9z6t56395060'

关于python - 将字符串转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46702585/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com