2019-08-04 Google Translate2: Python

1. set up anaconda (Python included)

download (for Linux only)
    wget https://repo.anaconda.com/archive/Anaconda3-2019.03-Linux-x86_64.sh

install
    bash Anaconda3-2019.03-Linux-x86_64.sh

create new env. (With Python3.7)
    conda create --name google_translate_py37 python=3.7

2. install dependencies

conda install -y requests xlrd openpyxl pandas

3. run python script

3.1 Google will frequent request with google-translate API

So please set up a proper time interval for each request like this: (set interval time: 3 seconds, and it can be set to a larger value according to your own situation)

image.png

3.2 run

source activate google_translate_py37
python simple_google_translate-20190804.py
  • 3.2.1 Ok to request
image.png
image.png
  • 3.2.2 Failed due to frequent requests
image.png

[Details]

  1. Script
import csv
import os
import requests
import sys

#import xlrd
import pandas as pd
import numpy as np


ERR_429     = 'request_err_429'
ERR_UNKNOWN = 'request_err_unknown'

new_xlsx_name  = 'google_translate.xlsx'
new_sheet_name = 'google_translate_sheet'


# https://www.jb51.net/article/163320.htm
def showExcelSheetHead(data_frame):
    #print('----------------------------------------------------------------------------------------')
    data = data_frame.head()
    print("[+] showExcelSheetHead:\n{}".format(data))


# https://blog.csdn.net/weixin_43245453/article/details/90747259
def selectExcelSheet(file_path):
    print('----------------------------------------------------------------------------------------')
    print("[+] selectExcelSheet")

    data = pd.read_excel(file_path, None)
    #print("sheets\t\t{}".format(data.keys()))

    sheets = []
    for i, sheet_name in enumerate(data.keys()):
        sheets.append(sheet_name)
        print("\t[-] sheet {}:\t{}".format(i, sheet_name))

    chooice = int(input('Please select a sheet [sheet number] '))
    return sheets[chooice]


def selectExcelTitle(file_path, sheet_name):
    print('----------------------------------------------------------------------------------------')
    print("[+] selectExcelColumn")
    
    sheet_content = pd.DataFrame(pd.read_excel(file_path, sheet_name))
    showExcelSheetHead(sheet_content)

    print()
    titles = []
    titles.append( (sheet_content.columns)[0] )
    titles.append( (sheet_content.columns)[1] )

    for i, title in enumerate(titles):
        print('\t[-] title {}:\t{}'.format(i, title))

    chooice = int(input('Please select a column (keywords_title) to translate [column number] '))
    return titles[chooice], sheet_content


def getExcelShape(data_frame):
    return data_frame.shape
    
def getExcelRows(data_frame):
    return data_frame.shape[0]
    
def getExcelColumns(data_frame):
    return data_frame.shape[1]


# http://pytolearn.csd.auth.gr/b4-pandas/40/moddfcols.html
def insertExcelRow(data_frame, row_index, row_list):
    # insert a row
    data_frame.loc[row_index] = row_list

def insertExcelColumn(data_frame, column_index, column_name, column_list):
    # insert a column
    data_frame.insert(column_index, column_name, column_list)

def appendExcelColumn(data_frame, column_name, column_list):
    # append a column
    #data_frame[column_name] = column_list

    # append an empty column
    data_frame[column_name] = pd.Series()

# https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html
# https://blog.csdn.net/sscc_learning/article/details/76993816
def updateExcelCell(data_frame, row_index, column_name, value):
    data_frame[column_name][row_index] = value


# Translate Excel columns
def translateExcelColumns(data_frame, keywords_title):
    print('----------------------------------------------------------------------------------------')
    print("[+] translateExcelColumns")

    global ERR_429
    global ERR_UNKNOWN
    global new_xlsx_name
    global new_sheet_name

    if new_sheet_name == '':
        new_xlsx_name  = input('Please name the new xlsx  [xlsx  name] ')
    if new_sheet_name == '':
        new_sheet_name = input('Please name the new sheet [sheet name] ')

    translation_title = 'Google Translate'
    appendExcelColumn(data_frame, translation_title, [])

    nrows = getExcelRows(data_frame)
    print('[*] number of keywords to be translated:\t{}\n\n'.format(nrows))

    for i in range(0, nrows):
        keywords = data_frame[keywords_title][i]
        #print("[-] translate keywords:", keywords)
        res = translateLine(keywords)

        if res == ERR_429:
            print('(T_T) You are requesting "Google Translate" too frequently, please have a rest...')
            return
        elif res == ERR_UNKNOWN:
            print('(T_T) Unknown error happened')
            return

        updateExcelCell(data_frame, i, translation_title, res)
        if i % 10 == 0:
            data_frame.to_excel(new_xlsx_name, sheet_name=new_sheet_name)


# simple way: ok
# https://blog.csdn.net/zcoutman/article/details/69062422
def translateLine(keywords):
    print("\t[-] translateLine:\t{}".format(keywords))

    global ERR_429
    global ERR_UNKNOWN

    # 1. isnan
    if type(keywords) == float:
        if np.isnan(keywords):
            #print("[-] keywords is nan:", keywords)
            return ''

    # 2. strip blank space
    keywords = str(keywords).strip()

    # 3. skip empty keywords
    if keywords == None:
        #print("[-] keywords is None:", keywords)
        return ''
    elif len(keywords) == 0:
        #print("[-] keywords len is 0:", keywords)
        return ''
    elif keywords.isspace():
        #print("[-] keywords is blank space:", keywords)
        return ''

    # 4. translate
    source_language = 'en'
    target_language = 'zh-CN'

    content = 'http://translate.google.cn/translate_a/single?client=gtx&sl=' + source_language + '&tl=' + target_language + '&dt=t&q=' + keywords
    response = requests.post(content)
    #print("[-] response: ", response)
    #print("[-] response status: ", response.status_code)

    if response.status_code == 200:
        res = response.json()
        #print("[-] res: ", res)

        search = res[0][0][1]
        result = res[0][0][0]
        print("\t\t\t\t---> {}".format(result))

    elif response.status_code == 429:
        result = ERR_429
    else:
        result = ERR_UNKNOWN

    return result
    

def selectExcelFile():
    print('----------------------------------------------------------------------------------------')
    print("[+] selectExcelFile")

    files = []
    for i, file in enumerate(os.listdir('./')):
        files.append(file)
        if file.endswith('.xlsx'):
            print('\t[-] file {}:\t{}'.format(i, file))

    chooice = int(input('Please select a xlsx file [file number] '))
    return files[chooice]


def translateOneWords(keywords):
    translateLine(keywords)


def translateExcel():
    file_path  = selectExcelFile()
    print('[*] file_path:\t{}'.format(file_path))

    sheet_name = selectExcelSheet(file_path)
    print('[*] sheet_name:\t{}'.format(sheet_name))

    keywords_title, data_frame = selectExcelTitle(file_path, sheet_name)
    print('[*] keywords_title:\t{}'.format(keywords_title))

    pd.set_option('mode.chained_assignment', None)
    translateExcelColumns(data_frame, keywords_title)


# start from here
if __name__ == '__main__':

    #translateOneWords('pancake')

    translateExcel()

    print('----------------------------------------------------------------------------------------')
最后编辑于
?著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,172评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,346评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事?!?“怎么了?”我有些...
    开封第一讲书人阅读 159,788评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,299评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,409评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,467评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,476评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,262评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,699评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,994评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,167评论 1 343
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,827评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,499评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,149评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,387评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,028评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,055评论 2 352

推荐阅读更多精彩内容