python - 将自定义字符串转换为字典
问题描述
您好,
我需要将这种类型转换string
为向下dict
string = "OS: Windows 7 SP1, Windows 8.1, Windows 10 (64bit versions only)Processor: Intel Core i5 2400s @ 2.5 GHz, AMD FX 6120 @ 3.5 GHz or betterMemory: 6 GB RAMGraphics: NVIDIA GeForce GTX 660 with 2 GB VRAM or AMD Radeon HD 7870, with 2 GB VRAM or better - See supported List"
信息和通信技术
requirements={
'Os':'Windows 7 SP1, Windows 8.1, Windows 10 (64bit versions only)',
'Processor':' Intel Core i5 2400s @ 2.5 GHz, AMD FX 6120 @ 3.5 GHz or better',
'Memory':'6 GB RAM',
'Graphics':'VIDIA GeForce GTX 660 with 2 GB VRAM or AMD Radeon HD 7870, with 2 GB VRAM or better - See supported List',
}
我试过这个
string = string.split(':')
并像这样用字典存储每个列表
requirements['Os'] = string[0]
requirements['Processor'] = string[1]
但这不是正确的方法!这给我带来了更多的错误。那么,这些东西是否有任何自定义功能或模块?
解决方案
我会使用正则表达式来捕获您想要的文本,因为输入字符串的实际格式不会改变。这应该给你想要的:
import re
string = "OS: Windows 7 SP1, Windows 8.1, Windows 10 (64bit versions only)Processor: Intel Core i5 2400s @ 2.5 GHz, AMD FX 6120 @ 3.5 GHz or betterMemory: 6 GB RAMGraphics: NVIDIA GeForce GTX 660 with 2 GB VRAM or AMD Radeon HD 7870, with 2 GB VRAM or better - See supported List"
matches = re.match(r'OS: (.+)Processor: (.+)Memory: (.+)Graphics: (.+)', string)
requirements = {
'Os': matches.group(1),
'Processor': matches.group(2),
'Memory': matches.group(3),
'Graphics': matches.group(4),
}
print(requirements)
正则表达式虽然有点不灵活,但我建议仅以此为起点。
见重新匹配