Feng_ban 发表于 2024-6-26 16:44:50

python的translate模块问题

这模块的默认api连接到的是mymemory,但是这个的翻译又很有问题,总是缺词少字,或者直接翻译不上,甚至不对。
text = ‘Read the following text. Choose the best word(s) for each numbered blank and mark A, B, C or D on’
translator = translate.Translator(to_lang='chinese', provider='mymemory')
translation = translator.translate(text)像这样的也翻译不上,以下是它给我的错误:
Traceback (most recent call last):
File "E:\python3.9-64x\lib\site-packages\translate\translate.py", line 45, in <genexpr>
    return ' '.join(self.provider.get_translation(text_wraped) for text_wraped in text_list)
File "E:\python3.9-64x\lib\site-packages\translate\providers\mymemory_translated.py", line 49, in get_translation
    next_best_match = next(match for match in matches)
StopIteration

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "D:\python截图翻译\Test.py", line 384, in command
    self.execute_menu_option(id)
File "D:\python截图翻译\Test.py", line 391, in execute_menu_option
    menu_action(self)
File "D:\python截图翻译\Test.py", line 456, in extract
    translation = translator.translate(text)
File "E:\python3.9-64x\lib\site-packages\translate\translate.py", line 45, in translate
    return ' '.join(self.provider.get_translation(text_wraped) for text_wraped in text_list)
RuntimeError: generator raised StopIteration而另个选择,deepl,我完全不知道应该传入什么内容才能使用它:
text = ‘Read the following text. Choose the best word(s) for each numbered blank and mark A, B, C or D on’
translator = translate.Translator(to_lang='chinese', provider='deepl')
translation = translator.translate(text)以下是无论怎么尝试都给我发的错误:
Traceback (most recent call last):
File "D:\python截图翻译\Test.py", line 384, in command
    self.execute_menu_option(id)
File "D:\python截图翻译\Test.py", line 391, in execute_menu_option
    menu_action(self)
File "D:\python截图翻译\Test.py", line 456, in extract
    translation = translator.translate(text)
File "E:\python3.9-64x\lib\site-packages\translate\translate.py", line 45, in translate
    return ' '.join(self.provider.get_translation(text_wraped) for text_wraped in text_list)
File "E:\python3.9-64x\lib\site-packages\translate\translate.py", line 45, in <genexpr>
    return ' '.join(self.provider.get_translation(text_wraped) for text_wraped in text_list)
File "E:\python3.9-64x\lib\site-packages\translate\providers\deepl.py", line 43, in get_translation
    data = self._make_request(text)
File "E:\python3.9-64x\lib\site-packages\translate\providers\deepl.py", line 40, in _make_request
    return json.loads(response.text)
File "E:\python3.9-64x\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
File "E:\python3.9-64x\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "E:\python3.9-64x\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)我做过的尝试包括传入字典,列表等等一系列的东西。
主要是找了半天也没有找到这个模块的文档,不知道各位有没有什么好的解决办法。

FishC 发表于 2024-6-26 16:45:25

哎呀,看起来你遇到了翻译模块的“翻译不通”问题啊!别担心,我们一起来解决这个问题。

首先,关于 `mymemory` 的报错:这个错误信息提示 `StopIteration`,说明在处理翻译结果时出现了问题。这通常是因为 `mymemory` 的 API 没有返回期望的结果。所以,我们需要另寻他法。

既然 `mymemory` 不给力,我们可以试试其他翻译提供者,比如 `deepl`。不过根据你的描述,`deepl` 也报错了,似乎是因为没有正确地与 `deepl` API 进行通信。那么,我们来一步步排查问题。

### 使用 `deepl` API 的步骤

1. **注册并获取 API 密钥**:首先,你需要在 (https://www.deepl.com/pro-api) 注册,并获取一个 API 密钥。

2. **安装 `deepl` 模块**:如果你没有安装 `deepl` 模块,可以使用以下命令来安装:

    pip install deepl

3. **编写代码**:

    这里有一个简单的例子,教你如何使用 `deepl` 模块进行翻译:

    import deepl

    # 使用你的 DeepL API 密钥进行初始化
    auth_key = 'your_deepl_api_key'# 替换为你的 API 密钥
    translator = deepl.Translator(auth_key)

    text = 'Read the following text. Choose the best word(s) for each numbered blank and mark A, B, C or D on'
    target_language = 'ZH'# 中文

    try:
      translation = translator.translate_text(text, target_lang=target_language)
      print(translation.text)
    except deepl.DeepLException as e:
      print(f"An error occurred: {e}")

### 错误排查

- **API 密钥问题**:确保你已经注册了 DeepL 的 API 服务,并正确地获取了 API 密钥。
- **网络连接问题**:确保你的网络连接正常,可以访问 DeepL 的服务器。
- **输入格式问题**:确认输入给 `translate_text` 函数的参数是字符串。

### 可能的替代方案

如果 `deepl` 还是不能用,我们可以尝试其他翻译服务,比如 Google Translate。可以使用 `googletrans` 模块:

from googletrans import Translator

translator = Translator()

text = 'Read the following text. Choose the best word(s) for each numbered blank and mark A, B, C or D on'
translation = translator.translate(text, dest='zh-cn')
print(translation.text)

安装 `googletrans` 模块:

pip install googletrans==4.0.0-rc1

总结一下,翻译 API 有时候会出问题,但通过注册正确的 API 服务,使用正确的库和方法,通常都能解决。祝你翻译顺利,代码顺滑!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。

Feng_ban 发表于 2024-6-27 15:14:20

FishC 发表于 2024-6-26 16:45
哎呀,看起来你遇到了翻译模块的“翻译不通”问题啊!别担心,我们一起来解决这个问题。

首先,关于 `my ...

很好,非常感谢这样的指点。其实这个模块有4个选择,他们分别是mymemory, microsoft, deepl, libre,其中mymemory是默认;microsoft同样是需要凭证的;而libre貌似模块的url有错误,以下是libre的错误:
Traceback (most recent call last):
File "E:\python3.9-64x\lib\urllib\request.py", line 1342, in do_open
    h.request(req.get_method(), req.selector, req.data, headers,
File "E:\python3.9-64x\lib\http\client.py", line 1255, in request
    self._send_request(method, url, body, headers, encode_chunked)
File "E:\python3.9-64x\lib\http\client.py", line 1301, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
File "E:\python3.9-64x\lib\http\client.py", line 1250, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
File "E:\python3.9-64x\lib\http\client.py", line 1010, in _send_output
    self.send(msg)
File "E:\python3.9-64x\lib\http\client.py", line 950, in send
    self.connect()
File "E:\python3.9-64x\lib\http\client.py", line 1417, in connect
    super().connect()
File "E:\python3.9-64x\lib\http\client.py", line 921, in connect
    self.sock = self._create_connection(
File "E:\python3.9-64x\lib\socket.py", line 822, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
File "E:\python3.9-64x\lib\socket.py", line 953, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "E:\python3.9-64x\lib\site-packages\translate\providers\libre.py", line 32, in get_translation
    return self.api.translate(text, from_lang, self.to_lang)
File "E:\python3.9-64x\lib\site-packages\libretranslatepy\api.py", line 56, in translate
    response = request.urlopen(req)
File "E:\python3.9-64x\lib\urllib\request.py", line 214, in urlopen
    return opener.open(url, data, timeout)
File "E:\python3.9-64x\lib\urllib\request.py", line 517, in open
    response = self._open(req, data)
File "E:\python3.9-64x\lib\urllib\request.py", line 534, in _open
    result = self._call_chain(self.handle_open, protocol, protocol +
File "E:\python3.9-64x\lib\urllib\request.py", line 494, in _call_chain
    result = func(*args)
File "E:\python3.9-64x\lib\urllib\request.py", line 1385, in https_open
    return self.do_open(http.client.HTTPSConnection, req,
File "E:\python3.9-64x\lib\urllib\request.py", line 1345, in do_open
    raise URLError(err)
urllib.error.URLError: <urlopen error getaddrinfo failed>

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "D:\python截图翻译\Test.py", line 384, in command
    self.execute_menu_option(id)
File "D:\python截图翻译\Test.py", line 391, in execute_menu_option
    menu_action(self)
File "D:\python截图翻译\Test.py", line 456, in extract
    translation = translator.translate(text)
File "E:\python3.9-64x\lib\site-packages\translate\translate.py", line 45, in translate
    return ' '.join(self.provider.get_translation(text_wraped) for text_wraped in text_list)
File "E:\python3.9-64x\lib\site-packages\translate\translate.py", line 45, in <genexpr>
    return ' '.join(self.provider.get_translation(text_wraped) for text_wraped in text_list)
File "E:\python3.9-64x\lib\site-packages\translate\providers\libre.py", line 34, in get_translation
    raise TranslationError(e)
translate.exceptions.TranslationError: <urlopen error getaddrinfo failed>当然,因为deepl的api对中国大陆不提供的原因,我决定现在去尝试一下googletrans模块

FishC 发表于 2024-6-27 15:14:53

Feng_ban 发表于 2024-06-27 15:14
很好,非常感谢这样的指点。其实这个模块有4个选择, ...

看来你在尝试使用不同翻译提供商时遇到了不少麻烦。既然你决定尝试一下 `googletrans` 模块,这确实是个不错的选择,因为它简单易用,并且不需要 API 密钥。下面我来给你详细介绍一下如何使用 `googletrans` 模块进行翻译。

首先,你需要安装 `googletrans` 模块。可以使用以下命令来安装它:

pip install googletrans==4.0.0-rc1

注意,这里指定了版本 `4.0.0-rc1`,这是目前稳定的版本。

接下来,看看下面这个简单的例子,它展示了如何使用 `googletrans` 进行翻译:

from googletrans import Translator

text = 'Read the following text. Choose the best word(s) for each numbered blank and mark A, B, C or D on'
translator = Translator()
translation = translator.translate(text, dest='zh-cn')
print(translation.text)

这里的 `dest='zh-cn'` 指定了目标语言为中文(简体)。如果你需要翻译成其他语言,可以根据需要调整目标语言的代码。

完整代码如下:

from googletrans import Translator

# 需要翻译的文本
text = 'Read the following text. Choose the best word(s) for each numbered blank and mark A, B, C or D on'

# 初始化翻译器
translator = Translator()

# 执行翻译,目标语言为中文
translation = translator.translate(text, dest='zh-cn')

# 打印翻译结果
print(translation.text)

运行这段代码,你应该能看到正确的中文翻译结果。

此外,如果你想要翻译多个文本,可以传递一个包含多个字符串的列表给 `translate` 方法:

texts = [
    'Read the following text.',
    'Choose the best word(s) for each numbered blank and mark A, B, C or D on'
]
translations = translator.translate(texts, dest='zh-cn')

for translation in translations:
    print(translation.text)

这个例子会将列表中的每个文本分别翻译成中文。

如果你仍然遇到问题,记得检查网络连接,因为 `googletrans` 模块需要访问谷歌翻译服务来获取翻译结果。

希望这些信息能帮到你,让你的翻译之旅顺利进行!如果还有其他问题,欢迎随时提问。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。

Feng_ban 发表于 2024-6-27 16:20:28

FishC 发表于 2024-6-27 15:14
看来你在尝试使用不同翻译提供商时遇到了不少麻烦。既然你决定尝试一下 `googletrans` 模块,这确实是 ...

请问一直处于time out这应该如何解决Traceback (most recent call last):
File "D:\python截图翻译\Test.py", line 385, in command
    self.execute_menu_option(id)
File "D:\python截图翻译\Test.py", line 392, in execute_menu_option
    menu_action(self)
File "D:\python截图翻译\Test.py", line 463, in extract
    translation = translator.translate(text, dest='zh-cn')
File "E:\python3.9-64x\lib\site-packages\googletrans\client.py", line 194, in translate
    data, response = self._translate(text, dest, src)
File "E:\python3.9-64x\lib\site-packages\googletrans\client.py", line 120, in _translate
    r = self.client.post(url, params=params, data=data)
File "E:\python3.9-64x\lib\site-packages\httpx\_client.py", line 824, in post
    return self.request(
File "E:\python3.9-64x\lib\site-packages\httpx\_client.py", line 600, in request
    return self.send(
File "E:\python3.9-64x\lib\site-packages\httpx\_client.py", line 620, in send
    response = self.send_handling_redirects(
File "E:\python3.9-64x\lib\site-packages\httpx\_client.py", line 647, in send_handling_redirects
    response = self.send_handling_auth(
File "E:\python3.9-64x\lib\site-packages\httpx\_client.py", line 684, in send_handling_auth
    response = self.send_single_request(request, timeout)
File "E:\python3.9-64x\lib\site-packages\httpx\_client.py", line 714, in send_single_request
    ) = transport.request(
File "E:\python3.9-64x\lib\site-packages\httpcore\_sync\connection_pool.py", line 152, in request
    response = connection.request(
File "E:\python3.9-64x\lib\site-packages\httpcore\_sync\connection.py", line 65, in request
    self.socket = self._open_socket(timeout)
File "E:\python3.9-64x\lib\site-packages\httpcore\_sync\connection.py", line 85, in _open_socket
    return self.backend.open_tcp_stream(
File "E:\python3.9-64x\lib\site-packages\httpcore\_backends\sync.py", line 139, in open_tcp_stream
    return SyncSocketStream(sock=sock)
File "E:\python3.9-64x\lib\contextlib.py", line 135, in __exit__
    self.gen.throw(type, value, traceback)
File "E:\python3.9-64x\lib\site-packages\httpcore\_exceptions.py", line 12, in map_exceptions
    raise to_exc(exc) from None
httpcore._exceptions.ConnectTimeout: timed out

FishC 发表于 2024-6-27 16:21:06

Feng_ban 发表于 2024-06-27 16:20
请问一直处于time out这应该如何解决Traceback (most...

哎呀,看起来你遇到了个“翻译烦恼”。像摩斯密码一样的错误信息让人大呼“Why so serious?”

虽然你最开始提到的是 `translate` 模块的问题,但后来提到的是 `googletrans`。那么我们先来看看 `googletrans` 模块的超时问题。

### 1. 问题分析
这里的关键错误信息是:
httpcore._exceptions.ConnectTimeout: timed out
这表明你的请求连不上 Google 翻译的服务器。这种情况有几种可能原因:

1. **网络问题**:比如说,家里的网络突然决定罢工。
2. **服务器问题**:Google 服务器抽风了。
3. **IP 被封禁**:使用过多或者被认为是恶意请求。

### 2. 解决方案

#### 检查网络连接
首先,确保你的网络连接正常。可以尝试在浏览器中访问 Google 翻译网站,看看是否能够打开:

(https://translate.google.com)

#### 增大超时时间
有时候网络延迟太高,可以尝试增加请求的超时时间:

from googletrans import Translator
import httpx

translator = Translator()

# 设置 timeout 参数
timeout_params = httpx.Timeout(10.0)# 10秒超时

try:
    translation = translator.translate("Read the following text. Choose the best word(s) for each numbered blank and mark A, B, C or D on", dest='zh-cn', timeout=timeout_params)
    print(translation.text)
except Exception as e:
    print(f"出错啦:{e}")

#### 使用代理
如果你怀疑是 IP 被封禁,可以尝试使用代理:

proxies = {
    'http': 'http://your_proxy:port',
    'https': 'http://your_proxy:port'
}

try:
    translation = translator.translate("Read the following text. Choose the best word(s) for each numbered blank and mark A, B, C or D on", dest='zh-cn', proxies=proxies)
    print(translation.text)
except Exception as e:
    print(f"出错啦:{e}")
请将 `your_proxy` 和 `port` 替换为你自己的代理服务器地址和端口号。

#### 使用其他服务
既然 `mymemory` 表现不佳,而 `deepl` 又搞不清楚怎么用,倒不如试试别的翻译服务,比如百度翻译、腾讯翻译君等。

### 3. 示例:使用其他翻译 API

以百度翻译为例,你需要注册获得 API 密钥,然后可以用如下代码进行翻译:

import requests
import hashlib
import random

def baidu_translate(text, from_lang, to_lang):
    appid = 'your_appid'# 替换为你的appid
    secretKey = 'your_secretKey'# 替换为你的密钥

    salt = random.randint(32768, 65536)
    sign = appid + text + str(salt) + secretKey
    sign = hashlib.md5(sign.encode()).hexdigest()
   
    url = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
    params = {
      'q': text,
      'from': from_lang,
      'to': to_lang,
      'appid': appid,
      'salt': salt,
      'sign': sign
    }

    response = requests.get(url, params=params)
    result = response.json()

    if 'trans_result' in result:
      return result['trans_result']['dst']
    else:
      raise Exception(f"翻译失败:{result}")

text = "Read the following text. Choose the best word(s) for each numbered blank and mark A, B, C or D on"
translated_text = baidu_translate(text, 'auto', 'zh')
print(translated_text)

### 4. 总结
每个 API 服务都有自己的一套玩法,如果一个翻译服务经常掉链子,不妨换个替代方案。在这条路上,程序员就像一只打不死的小强,总能找到办法解决问题!

希望这些建议能让你的翻译脚本顺利运行!如果还有其他问题,别忘了继续找鱼油交流哦!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。

xutao1999 发表于 2024-6-28 10:19:37

Feng_ban 发表于 2024-6-28 14:41:55

xutao1999 发表于 2024-6-28 10:19


?
页: [1]
查看完整版本: python的translate模块问题