分享

获取百度翻译的英文句子的读音

 行者花雕 2022-12-25 发布于北京
import requests
from io import BytesIO
from urllib.parse import quote
from docx import Document
import time

# 修改cookie
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0',
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
    'Accept-Encoding': 'gzip, deflate, br',
    'cookie': '...',
    'Upgrade-Insecure-Requests': '1',
    'TE': 'Trailers',
    'Pragma': 'no-cache',
    'Cache-Control': 'no-cache',
    'connection': 'keep-alive',
}
URL = "https://fanyi.baidu.com/gettts?lan=en&text=%s&spd=3&source=web"

session = requests.session()
maxlen = 2


def fanyi(no, sentence):
    """
    :param no: 序号
    :param sentence: 一段英文
    :return: 
    """
    print(sentence, end=" ")
    response = session.get(URL % quote(sentence), headers=headers)
    print("code: ", response.status_code)
    if response.status_code != 200:
        return False

    with open('./2021-03-08/' + str(no) + ".mp3", "wb") as f:
        soud = BytesIO(response.content)
        z = soud.getbuffer()
        f.write(z)
        f.flush()

    return True


def main():
    # 这个函数主要是为了获取文件中的英文,自行修改
    document = Document('./2021-03-08.docx')
    cnt = 0
    for para in document.paragraphs:
        text = para.text
        start, end = text.find('】'), text.find('^')
        if start == -1 or end == -1:
            continue
        cnt += 1

        no = str(cnt)
        if len(no) < maxlen:
            no = '0' * (maxlen - len(no)) + no

        fanyi(no, text[start + 1:end].strip())
        time.sleep(3)

    print(cnt)


if __name__ == '__main__':
    main()

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多