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

  1. 录音
  2. 获取token
  3. 语音识别
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]')
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐