一、引言




本号在文章《用Python写简单的机器翻译程序(1)》中给出了一个调用谷歌翻译网页版接口的程序,可以实现一个简单的机器翻译功能。这个程序有一定的局限性,就是每次能翻译的汉字数有限制。经反复试验发现:
每次运行程序最多能翻译1840个汉字(对应构造的网址包含16407个字符),再多一个汉字就得不到翻译结果。
每次运行程序最多能翻译5000个字符的英文文本(对应构造的网址包含7309个字符),再多一个字符就得不到翻译结果。
现在我们给出另外一个调用谷歌机器翻译的方案:用扩展库。
pip install googletrans-py
pip install googletrans

调用谷歌翻译扩展库只需要用4行代码就实现了一个机器翻译玩具系统,比调用谷歌翻译网页版接口的12行代码还要简单不少。
上述代码的运行结果如下:
I like kittens.
我们还可以翻译多行文本。

上述代码的运行结果如下:
原文本:春天来了!春天来了!我们几个孩子,脱掉棉袄,冲出家门,奔向田野,去寻觅春天。春天像个害羞的小姑娘,遮遮掩掩,躲躲藏藏。我们细心地找啊,找啊。小草从地下探出头来,那是春天的眉毛吧?早开的野花一朵两朵,那是春天的眼睛吧?树木吐出点点嫩芽,那是春天的音符吧?解冻的小溪叮叮咚咚,那是春天的琴声吧?春天来了!我们看到了她,我们听到了她,我们闻到了她,我们触到了她。她在柳枝上荡秋千,在风筝尾巴上摇啊摇;她在喜鹊、杜鹃嘴里叫,在桃花、杏花枝头笑……目标文本:spring is coming!spring is coming!A few children took off the cotton jacket, rushed out of the house, rushed to the field, and went to find spring.Spring is like a shy little girl, covering up, hiding from Tibet.We are looking for it carefully, looking for it.Xiao Cao poked from the ground underground, is it the eyebrows of spring?One or two wild flowers in early, is that spring eyes?The trees spit out a little bit of buds, is it the notes of spring, right?The thawed creek Ding Ding Ding, is it the sound of spring?spring is coming!We saw her, we heard her, we heard her, and we touched her.She swayed on the willow branches and shake it on the tail of the kite; she screamed in the mouth of the magpie and azalea, and laughed on the peach blossoms and apricot blooms ...
经测试,谷歌翻译扩展库每次汉译英调用可翻译不超过5000个汉字的汉语文本。
如果我们想英译汉,加一个参数就行。

英译汉每次最多能翻译多少英语文本,这个没有测试,想来应该有字符数或单词数限制。
目标语言还可以设置成其他语言类型,这个不再多说。
文章转载自语和言,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




