【4】python将翻译中文成英文,以字符串形式输出,然后改变字符串形式

def translationChtoEn(list):
    import urllib.request
    import urllib.parse
    import json

    while True:
        content = list
        if content == 'Q':
            break
        else:
            url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=http://www.youdao.com/'
            data = {}

            data['type'] = 'AUTO'
            data['i'] = content
            data['doctype'] = 'json'
            data['xmlVersion'] = '1.8'
            data['keyfrom'] = 'fanyi.web'
            data['ue'] = 'UTF-8'
            data['action'] = 'FY_BY_CLICKBUTTON'
            data['typoResult'] = 'true'

            data = urllib.parse.urlencode(data).encode('utf-8')
            response = urllib.request.urlopen(url, data)
            html = response.read().decode('utf-8')
            target = json.loads(html)
            results = target['translateResult'][0][0]['tgt']
            # print(results)
            return results
            # print('翻译的结果:%s' % target['translateResult'][0][0]['tgt'])

def get_EnglishTitleName(titleList):
    titleEnName = []
    for i in range(len(titleList)):
        titleEnName.append(translationChtoEn(titleList[i]))
        titleEnName[i] = titleEnName[i].title()             #首字母大写
        titleEnName[i] = titleEnName[i].replace(' ', '_')   #替换
        titleEnName[i] = titleEnName[i].replace('(', '_')
        titleEnName[i] = titleEnName[i].replace(')', '')
        titleEnName[i] = titleEnName[i].replace(',', '')
        titleEnName[i] = titleEnName[i].replace('/', '_')
    # print('The titleEnName is:',end='\t')
    # print(titleEnName)
    return titleEnName

if __name__=='__main__':
    titleList = ['中/国','北(京)','昌,平','北 服']
    print(str(translationChtoEn(titleList)))
    englishTitleName = get_EnglishTitleName(titleList)
    print(englishTitleName)
    englishTitleNameTemp = ['']
    for i in range(len(englishTitleName)):
        englishTitleNameTemp.append(englishTitleName[i])

print(englishTitleNameTemp)

【4】python将翻译中文成英文,以字符串形式输出,然后改变字符串形式_第1张图片

你可能感兴趣的:(python)