美文网首页
有道翻译单词本导入助手

有道翻译单词本导入助手

作者: 安迹 | 来源:发表于2020-04-07 00:31 被阅读0次

自己做的一个可以将单词txt文件转为有道翻译可导入的xml文件形式,单词txt文件的形式要满足每行只有一个单词。
做的很简陋,建议配合有道背单词app使用。
源码:

# -*- coding: utf-8 -*-
import sys
import uuid
import requests
import hashlib
import time
import time
#常量定义
YOUDAO_URL = 'https://openapi.youdao.com/api'
app_key = ""   # 应用密钥
app_id = ""   # 应用id
data = {
      'from':"en",   # 源语言
      'to':"zh-CHS",   # 翻译语言
      'signType':"v3",   # 签名类型,固定值
}
def encrypt(signStr):
    hash_algorithm = hashlib.sha256()
    hash_algorithm.update(signStr.encode('utf-8'))
    return hash_algorithm.hexdigest()

def truncate(q):
    if q is None:
        return None
    size = len(q)
    return q if size <= 20 else q[0:10] + str(size) + q[size - 10:size]
def getWordMetaData(): #获取元数据
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    return requests.post(YOUDAO_URL, data=data, headers=headers).json()
def parasWordMetaData(): # 将元数据解析成XML代码
    mean = ""
    wordMetaData = getWordMetaData()
    basicMean= ""
    if "translation" in wordMetaData: #将翻译结果写入
        for translation in wordMetaData["translation"]:
            basicMean +=translation
    wordData = ("<item><word>"+data["q"]+"</word>"
     "  <trans><![CDATA["+basicMean+"]]></trans>"
     "  <phonetic><![CDATA[[""]]]></phonetic>"
     "  <tags>"+"tagName"+"</tags>"
     "  <progress>-1</progress>"
    "</item>")
    return wordData

def updateData(translate_text): #更新要翻译的英语单词
    if(len(translate_text) <= 20):
        input_text = translate_text 
    # 当文本长度大于20时,进行特殊处理
    elif(len(translate_text) > 20):
      input_text = translate_text[:10] + str(len(translate_text)) + translate_text[-10:]   
    time_curtime = int(time.time())   # 秒级时间戳获取

    uu_id = uuid.uuid4()   # 随机生成的uuid数,为了每次都生成一个不重复的数。

    sign = hashlib.sha256((app_id + input_text + str(uu_id) + str(time_curtime) + app_key).encode('utf-8')).hexdigest()   # sign生成
    data["q"] = translate_text
    data["appKey"] = app_id
    data["salt"] = uu_id
    data["sign"] = sign
    data["curtime"] = time_curtime
def readWordByFile(): #从文件中获取要翻译的英语单词
    wordList = list()
    f = open("yourWords.txt", encoding="utf-8")
    for t in f.readlines():
        wordList.append(t.replace("\n",""))
    return wordList 

if __name__ == '__main__':
    xmlFile = open("outputFile.xml","w+",encoding="utf-8")
    xmlFile.write("<wordbook>") #XML文件的开头
    wordList = readWordByFile()
    for word in wordList:
        updateData(word)
        wordData = parasWordMetaData()
        xmlFile.write(str(wordData))
    xmlFile.write("</wordbook>") #XML文件的结尾
    xmlFile.flush()
    xmlFile.close()
    print("success!")

相关文章

网友评论

      本文标题:有道翻译单词本导入助手

      本文链接:https://www.haomeiwen.com/subject/wfpwphtx.html