python获取六级单词发音mp3文件
近期因为一些需求,一直在学习英语发音,但是苦于自己的水平太渣,于是就想起了可以调用有道的api接口,得到单词的正宗英美发音。
废话不多说,直接贴图展示:
1.原料准备
- python3.X 并安装好套件os及requests
- 实现准备好要发音的单词文件,此处我准备的是六级单词,我会将资料上传,大家可以再次尝试
- 除此之外你还需要了解有道的api接口使用
1.1 有道英美发音api接口介绍
美音
http://dict.youdao.com/dictvoice?type=0&audio=
英音:
http://dict.youdao.com/dictvoice?type=1&audio=
如果我们要查询单词accept的发音,那么我们就可以直接将所要查询单词置于“=”后即可。eg.
http://dict.youdao.com/dictvoice?type=1&audio=accept
这里仅展示英氏发音,美式发音操作方法类似。
2.代码内容
代码很简单,相信大家很容易理解,在这里就不多说废话了。直接上代码:
# @Time : 2020/3/23 14:26
# @Author : kingback
# @File : 六级单词发音.py
# @Software: PyCharm
# 下载MP3文件到本地
import os
import requests
def DownloadFile(mp3_url, save_url,file_name):
try:
if mp3_url is None or save_url is None or file_name is None:
print('参数错误')
return None
# 文件夹不存在,则创建文件夹
folder = os.path.exists(save_url)
if not folder:
os.makedirs(save_url)
# 读取MP3资源
res = requests.get(mp3_url,stream=True)
# 获取文件地址
file_path = os.path.join(save_url, file_name)
print('开始写入文件:', file_path)
# 打开本地文件夹路径file_path,以二进制流方式写入,保存到本地
with open(file_path, 'wb') as fd:
for chunk in res.iter_content():
fd.write(chunk)
print(file_name+' 成功下载!')
except:
print("程序错误")
if __name__ == "__main__":
# MP3保存文件夹
save_url=r'E:\Google_jump_vpn\baiduyunpan\Music\六级单词发音\单词'
# MP3文件名
read_url=r'E:\Google_jump_vpn\baiduyunpan\Music\六级单词发音\六级单词英文版.txt'
file = open(read_url)
for line in file:
# MP3源地址url
url = 'http://dict.youdao.com/dictvoice?type=1&audio='
line = line.strip('\n')
file_name =line
print(file_name)
file_name =file_name+ '.mp3'
url=url+line
DownloadFile(url, save_url, file_name)
file.close()
3.单词发音文件及六级单词txt
获得到的六级单词英式发音mp3文件,我将其打包为一个zip文件,附在这里:
发音文件下载链接: