gpt4 book ai didi

python - 如何告诉 Googletrans 忽略某些部分?

转载 作者:太空宇宙 更新时间:2023-11-04 04:20:51 24 4
gpt4 key购买 nike

我想使用 googletrans 来使用 Google 翻译 API。但是,有些字符串中有变量名:

User "%(first_name)s %(last_name)s (%(email)s)" has been deleted.

如果我通过 googletrans 使用它,我会得到

from googletrans import Translator
translator = Translator()
translator.translate(u'User "%(first_name)s %(last_name)s (%(email)s)" has been assigned.', src='en', dest='fr').text

我得到以下信息:

L'utilisateur "% (first_name) s% (last_name) s (% (email) s)" a été affecté.

但是,“%(first_name) s% (last_name)s (%(email)s)”引入了一些字符串。有没有解决的办法?我已经尝试过:

u'User "<span class="notranslate">%(first_name)s %(last_name)s (%(email)s)</span>" has been assigned.'

最佳答案

Googletrans 似乎没有动过,例如 __1__。因此,您可以将 %(first_name)s 替换为 __0__,将 %(last_name)s 替换为 __1__,等等。在你翻译之前,然后在之后恢复变量。这里的代码可以做到这一点:

from googletrans import Translator
import re

translator = Translator()
txtorig = u'User "%(first_name)s %(last_name)s (%(email)s)" has been assigned.'

# temporarily replace variables of format "%(example_name)s" with "__n__" to
# protect them during translate()
VAR, REPL = re.compile(r'%\(\w+\)s'), re.compile(r'__(\d+)__')
varlist = []
def replace(matchobj):
varlist.append(matchobj.group())
return "__%d__" %(len(varlist)-1)
def restore(matchobj):
return varlist[int(matchobj.group(1))]

txtorig = VAR.sub(replace, txtorig)
txttrans = translator.translate(txtorig, src='en', dest='fr').text
txttrans = REPL.sub(restore, txttrans)

print(txttrans)

结果如下:

L'utilisateur "%(first_name)s %(last_name)s (%(email)s)" a été attribué.

关于python - 如何告诉 Googletrans 忽略某些部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54503927/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com