2017-05-07 59 views
0

我知道,有着名的Python配置解析器,但我認爲對於這種配置格式,解析器不會是最好的選擇。python從配置文件提取值

"AppState" 
{ 
    "appid"  "740" 
    "Universe"  "1" 
    "name"  "Counter-Strike Global Offensive - Dedicated Server" 
    "StateFlags"  "4" 
    "installdir"  "Counter-Strike Global Offensive Beta - Dedicated Server" 
    "LastUpdated"  "1492880350" 
    "UpdateResult"  "0" 
    "SizeOnDisk"  "14563398502" 
    "buildid"  "1771538" 
    "LastOwner"  "76561202168992874" 
    "BytesToDownload"  "6669177712" 
    "BytesDownloaded"  "6669177712" 
    "AutoUpdateBehavior"  "0" 
    "AllowOtherDownloadsWhileRunning"  "0" 
    "UserConfig" 
    { 
    } 
    "MountedDepots" 
    { 
     "731"  "3148506631334968252" 
     "740"  "8897003951704178635" 
    } 
} 

例如如何以最佳方式提取「buildid」的值?由於我需要多次使用配置文件工作,我只是尋找這種格式的最簡單的方法。

+0

你如何得到這個配置文件?上游解決問題可能更容易,也更穩健。爲什麼不使用合法的JSON,它可以通過正確的模塊輕鬆解析? – timgeb

回答

0

如果你可以看到它作爲一個普通的文件使用:

import re 
with open('myfile.extension') as data: 
    for line in data: 
     if 'buildid' in line: 
      print re.findall('\d+', line) 
      break 
0

Python 2解決方案:

with open("config.txt","r") as fp: 
    line_list = [c.strip() for c in fp.readlines()] 
    for line in line_list: 
     if "buildid" in line: 
      buildid = line.split()[1] 
      print int(buildid[1:-1]) 
      break 

輸出:

1771538 

config.txt包含:

"AppState" 
{ 
    "appid"  "740" 
    "Universe"  "1" 
    "name"  "Counter-Strike Global Offensive - Dedicated Server" 
    "StateFlags"  "4" 
    "installdir"  "Counter-Strike Global Offensive Beta - Dedicated Server" 
    "LastUpdated"  "1492880350" 
    "UpdateResult"  "0" 
    "SizeOnDisk"  "14563398502" 
    "buildid"  "1771538" 
    "LastOwner"  "76561202168992874" 
    "BytesToDownload"  "6669177712" 
    "BytesDownloaded"  "6669177712" 
    "AutoUpdateBehavior"  "0" 
    "AllowOtherDownloadsWhileRunning"  "0" 
    "UserConfig" 
    { 
    } 
    "MountedDepots" 
    { 
     "731"  "3148506631334968252" 
     "740"  "8897003951704178635" 
    } 
} 

N.B .:如果可能,請使用適當的JSON作爲配置文件。使用JSON是安全的。

+0

是的,我喜歡JSON,但可悲的是這個配置不是由我自己生成:(。 – kreishna

+0

對不起,聽到這個。上面的代碼在這種情況下工作正常嗎? – arsho