我正在尝试将多种语言的单词列表翻译成英文,我尝试使用googletrans库,它只用一个词就可以正常工作,但是当循环运行时,它使我受阻,经过一些研究,我了解到这是因为Google Restructions,所以我安装了nordvpn。
在此代码中,我每次Google阻止我时都试图从VPN连接断开连接,因此我可以更改IP地址。
这是我的代码
def translate_text(text, dest_language="en"):
# Used to translate using the googletrans library
import json
translator = googletrans.Translator()
try:
translation = translator.translate(text=text, dest=dest_language)
print(translation)
except json.decoder.JSONDecodeError:
# api call restriction
process = subprocess.Popen(["nordvpn", "d"], shell = True,stdout=subprocess.PIPE)
process.wait()
process = subprocess.Popen(["nordvpn", "c", "canada"] , shell = True , stdout=subprocess.PIPE)
process.wait()
return translate_text(text=text, dest_language=dest_language)
return translation
#translate to EN and remove EN stopwords
ListCapTranslated = []
for row in ListCaptionsCleanFiltred:
print(row)
# REINITIALIZE THE API
newrow = translate_text(row, dest_language="en")
ListCapTranslated.append(newrow)
我正在使用子进程库来使用CMD命令与VPN连接和断开连接。而且有效。
但是经过一些迭代后,我得到了这个错误:
ConnectionError :('连接被中止。,RemoteDisconnected('远端封闭的连接,没有响应'))
我是StackOverflow的新手,但我在此线程(GoogleTrans API Error - Expecting value: line 1 column 1 (char 0))中看到您关于此问题的文章,并应用了相同的代码(请参见下文)。
import googletrans
import subprocess
import os
import random
import json
SERVERS = ["South Africa", "Egypt", "Australia", "New Zealand", "South Korea", "Singapore",
"Hong Kong", "Indonesia", "Thailand", "Japan", "Malaysia", "United Kingdom", "Netherlands", "Germany",
"France", "Belgium", "Switzerland", "Sweden", "Spain", "Denmark", "Italy", "Norway", "Austria",
"Romania", "Luxembourg", "Poland", "Finland", "Hungary", "Latvia",
"Iceland", "Bulgaria", "Croatia", "Portugal", "Albania", "Ireland", "Slovakia",
"Cyprus", "Estonia", "Greece", "Serbia", "Slovenia",
"Macedonia", "India", 'United States', 'Canada', "Argentina", "Chile"]
def SelectServer(l):
return random.choice(l)
def translate_text(text, dest_language="en"):
# Used to translate using the googletrans library
translator = googletrans.Translator()
try:
translation = translator.translate(text=text, dest=dest_language)
except json.decoder.JSONDecodeError:
# api call restriction
os.chdir("C:/Program Files (x86)/NordVPN/")
print("exception !! disconnect from VPN...")
process = subprocess.Popen(["nordvpn", "-d"],
shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process.wait()
time.sleep(10)
srv = SelectServer(SERVERS)
print("Connect to server in: " + srv + "...")
process = subprocess.Popen(["nordvpn", "-c", "-g", {srv}],
shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process.wait()
time.sleep(60)
return translate_text(text=text, dest_language=dest_language)
return translation.text
reviewsX["translation"] = reviewsX["review"].map(lambda x: translate_text(x))
但是,不幸的是,我仍然收到此错误:request.exceptions.ConnectionError :(“连接已终止。”,RemoteDisconnected(“远端封闭的无响应的连接”))
据我所知,您已经解决了这个错误,如果您也能帮助我,我将非常感谢。您是否知道此错误是什么意思,或者可能是什么原因?
非常感谢您!