您的位置:首页 > 编程语言 > Python开发

python-21-如何读写json数据?如何解析简单的xml文档?

2017-05-06 13:38 821 查看


这里老师讲了一个小例子,调用百度的语音识别API来实现语音识别。大概过程是:

录音

获取token

语音识别

import json

# dumps方法可以把一个python对象转换成json的字符串
l = [1,2,'abc',{'name':'Bob','age':10}]
print(json.dumps(l))
#有些转换差别很大,有些转换差别很小,
d = {'b':None,'a':5,'c':'abc'}
print(json.dumps(d))
# 注意:转化的json字符串是带空格的。dumps有一个参数separators,设置分隔符
json.dumps(l,separators=[',',':'])
# dumps有一个参数sort_keys,排序,默认是False
json.dumps(l,sort_keys=True)

# loads方法可以把一个json的字符串转换成python对象
l2 = json.loads('[1, 2, "abc", {"name": "Bob", "age": 10}]')
print(l2)

#load,dump 和 loads,dumps的差异是接口是文件




解析xml文档





<?xml version="1.0" encoding="UTF-8"?>
<recipe type="dessert">
<recipename cuisine="american" servings="1">Ice Cream Sundae</recipename>
<ingredlist>
<listitem><quantity units="cups">0.5</quantity>
<itemdescription>vanilla ice cream</itemdescription></listitem>
<listitem><quantity units="tablespoons">3</quantity>
<itemdescription>chocolate syrup or chocolate fudge</itemdescription></listitem>
<listitem><quantity units="tablespoons">1</quantity>
<itemdescription>nuts</itemdescription></listitem>
<listitem><quantity units="each">1</quantity>
<itemdescription>cherry</itemdescription></listitem>
</ingredlist>
<utensils>
<listitem><quantity units="each">1</quantity>
<utensilname>bowl</utensilname></listitem>
<listitem><quantity units="each">1</quantity>
<utensilname>spoons</utensilname></listitem>
<listitem><quantity units="each">1</quantity>
<utensilname>ice cream scoop</utensilname></listitem>
</utensils>
<directions>
<step>Using ice cream scoop, place vanilla ice cream into bowl.</step>
<step>Drizzle chocolate syrup or chocolate fudge over the ice cream.</step>
<step>Sprinkle nuts over the mound of chocolate and ice cream.</step>
<step>Place cherry on top of mound with stem pointing upward.</step>
<step>Serve.</step>
</directions>
<variations>
<option>Replace nuts with raisins.</option>
<option>Use chocolate ice cream instead of vanilla ice cream.</option>
</variations>
<preptime>5 minutes</preptime>
</recipe>




- parse将返回一个ElementTree的对象

- 得到根节点et.getroot(),会得到元素对象

from xml.etree.ElementTree import parse
f = open('dome.xml')
et = parse(f)

root = et.getroot()

print(root.getchildren())

for child in root:
#属性名为cuisine
print(child.get('cuisine'))

#标签名为listitem
print(root.find('listitem'))
print(root.findall('listitem'))

#得到一个生成器对象,可以用来迭代,只会得到直接子元素,也就是儿子
print(root.iterfind('listitem'))

for e in root.iterfind('quantity'): print(e.get('each'))

#得到一个生成器对象,可以用来迭代,得到所有的子节点
print(list(root.iter('quantity')))

for e in root.iter('quantity'): print(e.get('units'))

#匹配quantity下的所有节点
root.findall(('quantity/*'))

#找到所有的rank节点,.当前对象,..父亲对象
root.findall('.//rank')

#country包涵name方法
root.findall('country[@name]')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: