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('----------------------------------------------------------------------------------------')
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末革半,一起剝皮案震驚了整個濱河市碑定,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌又官,老刑警劉巖延刘,帶你破解...
    沈念sama閱讀 216,324評論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異六敬,居然都是意外死亡碘赖,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,356評論 3 392
  • 文/潘曉璐 我一進店門外构,熙熙樓的掌柜王于貴愁眉苦臉地迎上來普泡,“玉大人,你說我怎么就攤上這事审编『嘲啵” “怎么了?”我有些...
    開封第一講書人閱讀 162,328評論 0 353
  • 文/不壞的土叔 我叫張陵垒酬,是天一觀的道長砰嘁。 經(jīng)常有香客問我件炉,道長,這世上最難降的妖魔是什么矮湘? 我笑而不...
    開封第一講書人閱讀 58,147評論 1 292
  • 正文 為了忘掉前任斟冕,我火速辦了婚禮,結(jié)果婚禮上板祝,老公的妹妹穿的比我還像新娘宫静。我一直安慰自己,他們只是感情好券时,可當我...
    茶點故事閱讀 67,160評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著伏伯,像睡著了一般橘洞。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上说搅,一...
    開封第一講書人閱讀 51,115評論 1 296
  • 那天炸枣,我揣著相機與錄音,去河邊找鬼弄唧。 笑死适肠,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的候引。 我是一名探鬼主播侯养,決...
    沈念sama閱讀 40,025評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼澄干!你這毒婦竟也來了逛揩?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,867評論 0 274
  • 序言:老撾萬榮一對情侶失蹤麸俘,失蹤者是張志新(化名)和其女友劉穎辩稽,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體从媚,經(jīng)...
    沈念sama閱讀 45,307評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡逞泄,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,528評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了拜效。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片喷众。...
    茶點故事閱讀 39,688評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖拂檩,靈堂內(nèi)的尸體忽然破棺而出侮腹,到底是詐尸還是另有隱情,我是刑警寧澤稻励,帶...
    沈念sama閱讀 35,409評論 5 343
  • 正文 年R本政府宣布父阻,位于F島的核電站愈涩,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏加矛。R本人自食惡果不足惜履婉,卻給世界環(huán)境...
    茶點故事閱讀 41,001評論 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望斟览。 院中可真熱鬧毁腿,春花似錦、人聲如沸苛茂。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,657評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽妓羊。三九已至胯究,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間躁绸,已是汗流浹背裕循。 一陣腳步聲響...
    開封第一講書人閱讀 32,811評論 1 268
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留净刮,地道東北人剥哑。 一個月前我還...
    沈念sama閱讀 47,685評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像淹父,于是被迫代替她去往敵國和親株婴。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,573評論 2 353

推薦閱讀更多精彩內(nèi)容