簡體   English   中英

Python字典轉換為json或yaml

[英]Python dictionary converting to json or yaml

我已經解析了一個字符串並將其轉換為字典。 但是我希望能夠從字典中獲取更多信息,並且我認為創建子文件或yaml文件會更有用。 請隨時評論解決此問題的另一種方法。

import re
regex = '(\w+) \[(.*?)\] "(.*?)" (\d+) "(.*?)" "(.*?)"'
sample2= 'this [condo] "number is" 28 "owned by" "james"'
patern = '(?P<host>\S+)\s(?P<tipe>\[\w+\])\s(?P<txt>"(.*?))\s(?P<number>\d+)\s(?P<txt1>"\w+\s\w+")\s(?P<owner>"\w+)'
m =re.match(patern, sample2)
res = m.groupdict()
print res

我會得到:

{'tipe': '[condo]', 'number': '28', 'host': 'this', 'owner': '"james', 'txt': '"number is"', 'txt1': '"owned by"'}

我希望能夠按房主姓名排序並寫出房屋類型和房號。 例如:

詹姆斯:{type:condo,number:28}

或其他建議?

json vs yaml的問題歸結為您要保存的數據在做什么? 如果要在JS或其他python腳本中重復使用數據,則可以使用JSON。 如果您在使用YAML的產品中使用它,請使用YAML。 但是就您的問題而言,除非您的數據有特定的最終游戲或用例,否則格式無關緊要,您甚至可以執行典型的TSV / CSV,並且將是相同的。

回答有關如何對json進行字典操作的問題。

從您的示例中創建出res字典。

import json
with open('someFile.json', 'wb') as outfile:
     json.dump(res, outfile)

您的輸出文件someFile.json將成為您的字典res

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM