1. 程式人生 > 其它 >googletrans 報錯解決方法【httpcore,JSONDecodeError】

googletrans 報錯解決方法【httpcore,JSONDecodeError】

googletrans json.decoder.JSONDecodeError: Extra data:
httpcore._exceptions.ConnectTimeout: timed out

完成以下兩步:
1.使用 pip install google_trans_new https://blog.csdn.net/a1397852386/article/details/111479024 2.手動修改google_trans_new庫一行程式碼 https://stackoverflow.com/questions/68214591/python-google-trans-new-translate-raises-error-jsondecodeerror-extra-data Change line 151 in google_trans_new/google_trans_new.py which is: response = (decoded_line + ']') to response = decoded_line # 首先初始化2條正樣本語句,和兩條負樣本語句 p_sample1 = "酒店設施非常不錯" p_sample2 = "這家價格便宜" n_sample1 = "拖鞋都發黴了,太差了" n_sample2 = "電視不好用,沒有看到足球" # # 匯入google翻譯介面工具 # from googletrans import Translator # # 例項化翻譯物件 # translator = Translator() # # # 先進行中文到韓文的翻譯 # translations = translator.translate([p_sample1,p_sample2,n_sample1,n_sample2],dest='ko') # # # 獲得翻譯成韓文後的文字結果 # ko_result = list(map(lambda x: x.text, translations)) # # print("中間翻譯結果韓文是:") # print(ko_result) # # # 接下來進行回譯 # translations = translator.translate(ko_result,dest='zh-cn') # cn_result = list(map(lambda x: x.text,translations)) # print("回譯得到的增強中文文字是:") # print(cn_result) from google_trans_new import google_translator # 例項化翻譯物件 translator = google_translator(timeout=10) print([p_sample1,p_sample2,n_sample1,n_sample2]) translations = [] # 先進行中文到韓文的翻譯 for text in [p_sample1,p_sample2,n_sample1,n_sample2]: translations.append(translator.translate(text, 'ko')) # 獲得翻譯成韓文後的文字結果 ko_result = translations print("中間翻譯結果韓文是:") print(ko_result) # 接下來進行回譯 translations = translator.translate(ko_result,'zh-cn') cn_result = translations print("回譯得到的增強中文文字是:") print(cn_result)