[英]Convert Custom String to Dict
你好,我需要將這種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)
不過,正則表達式有點不靈活,我建議只使用它作為起點。
見重新匹配
這是一種替代的非正則表達式解決方案,盡管正則表達式原則上可能更高效、更干凈:
input_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"
# Splits by space
input_string = input_string.split()
# Assumes the keys are exactly like listed - including uppercase letters
key_list = ["OS", "Processor", "Memory", "Graphics"]
key_ind = []
output = {}
# Collect indices corresponding to each key
for key in key_list:
for idx, el in enumerate(input_string):
if key in el:
key_ind.append(idx)
break
# Build the dictionary
for idx, key in enumerate(key_list):
if idx + 1 >= len(key_list):
output[key] = (' ').join(input_string[key_ind[idx]+1:])
else:
lp_idx = input_string[key_ind[idx+1]].find(key_list[idx+1])
lp = input_string[key_ind[idx+1]][:lp_idx]
output[key] = (' ').join(input_string[key_ind[idx]+1:key_ind[idx+1]]) + ' ' + lp
print(output)
這里首先根據空格分割字符串,然后代碼找到包含未來字典的鍵標簽的每個代碼塊的位置。 在存儲每個鍵的索引后,代碼基於它們構建字典,最后一個元素是一個特例。
對於除 last 之外的所有元素,代碼還提取了 next key 之前的信息。 這假設在下一個鍵和要為當前鍵存儲的文本的最后一部分之間沒有空格,即它始終是(64bit versions only)Processor:
而不是(64bit versions only) Processor:
-如果您不能做出這個假設,您將需要擴展此代碼以覆蓋帶有空格的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.