GithubHelp home page GithubHelp logo

terryyin / translate-python Goto Github PK

View Code? Open in Web Editor NEW
719.0 18.0 155.0 162 KB

Online translation as a Python module & command line tool. No key, no authentication needed.

License: MIT License

Makefile 3.37% Python 94.22% Nix 2.41%

translate-python's Introduction

Translate Tool in Python

PyPI latest PyPI Version PyPI License Docs Travis Build Status

Translate is a simple but powerful translation tool written in python with with support for multiple translation providers. By now we offer integration with Microsoft Translation API, Translated MyMemory API, LibreTranslate, and DeepL's free and pro APIs

Why Should I Use This?

The biggest reason to use translate is to make translations in a simple way without the need of bigger effort and can be used as a translation tool like command line

Installation

$ pip install translate

Or, you can download the source and

$ python setup.py install

Prefix 'sudo' if you encounter a problem.

Features

  • Translate your output in real time
  • Do translation in your terminal using the command line

Usage

In your command-line:

$ translate-cli -t zh "This is a pen."

Translation: 这是一支笔
-------------------------
Translated by: MyMemory

Or

$ translate-cli -t zh "This is a pen." -o
这是一支笔

Options

$ translate-cli --help
Usage: __main__.py [OPTIONS] TEXT...

  Python command line tool to make online translations

  Example:

       $ translate-cli -t zh the book is on the table
       碗是在桌子上。

  Available languages:

       https://en.wikipedia.org/wiki/ISO_639-1
       Examples: (e.g. en, ja, ko, pt, zh, zh-TW, ...)

Options:
  --version                 Show the version and exit.
  --generate-config-file    Generate the config file using a Wizard and exit.
  -f, --from TEXT           Sets the language of the text being translated.
                            The default value is 'autodetect'.
  -t, --to TEXT             Set the language you want to translate.
  -p, --provider TEXT       Set the provider you want to use. The default
                            value is 'mymemory'.
  --secret_access_key TEXT  Set the secret access key used to get provider
                            oAuth token.
  -o, --output_only         Set to display the translation only.
  -r, --region TEXT         Set to pass a region in to API calls that require it.
  --help                    Show this message and exit.

Change Default Languages

In ~/.python-translate.cfg:

[DEFAULT]
from_lang = autodetect
to_lang = de
provider = mymemory
secret_access_key =

The cfg is not for use as a Python module.

or run the command line and follow the steps:

$ translate-cli --generate-config-file
Translate from [autodetect]:
Translate to: <language you want to translate>
Provider [mymemory]:
Secret Access Key []:

Use As A Python Module

In [1]: from translate import Translator
In [2]: translator = Translator(to_lang="zh")
In [3]: translation = translator.translate("This is a pen.")
Out [3]: 这是一支笔

The result is usually a unicode string.

Use a different translation provider

In [1]: from translate import Translator
In [2]: to_lang = 'zh'
In [3]: secret = '<your secret from Microsoft or DeepL>'
In [4]: translator = Translator(provider='<the name of the provider, eg. microsoft or deepl>', to_lang=to_lang, secret_access_key=secret)
In [5]: translator.translate('the book is on the table')
Out [5]: '碗是在桌子上。'

The DeepL Provider

To use DeepL's pro API, pass an additional parameter named pro to the Translator object and set it to True and use your pro authentication key as the secret_access_key

In: translator = Translator(provider='microsoft', to_lang=to_lang, secret_access_key=secret, pro=True)

Documentation

Check out the latest translate documentation at Read the Docs

Contributing

Please send pull requests, very much appreciated.

  1. Fork the repository on GitHub.
  2. Make a branch off of master and commit your changes to it.

3. (Optional) if you want an isolated environment, you can install nixOS (https://nixos.org) and run nix-shell --pure under the project folder 3. Install requirements. pip install -r requirements-dev.txt 4. Install pre-commit. pre-commit install 5. Run the tests with py.test -vv -s 6. Create a Pull Request with your contribution.

translate-python's People

Contributors

adrian-valente avatar azin-z avatar bolkin avatar cleberzavadniak avatar cruderags avatar feetstv avatar godiard avatar hanxiaomax avatar kamiel79 avatar karimk123 avatar kxrob avatar magnunleno avatar mattfellows avatar michalisioak avatar mketab avatar mutabilitas avatar naveenfogat avatar pj-finlay avatar pringon avatar rhenter avatar terryyin avatar thesage21 avatar timgates42 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

translate-python's Issues

Error when running "from translate import Translator"

I am writing a plex agent which uses python 2.7 and I get the following error:

` File "C:\Program Files (x86)\Plex\Plex Media Server\Resources\Plug-ins-186bae04e\Framework.bundle\Contents\Resources\Versions\2\Python\Framework\core.py", line 608, in start
self.sandbox.execute(self.init_code)

File "C:\Program Files (x86)\Plex\Plex Media Server\Resources\Plug-ins-186bae04e\Framework.bundle\Contents\Resources\Versions\2\Python\Framework\code\sandbox.py", line 256, in execute
exec(code) in self.environment

File "C:\Users\jphud\AppData\Local\Plex Media Server\Plug-ins\GEVI.bundle\Contents\Code_init_.py", line 107, in
import utils

File "C:\Program Files (x86)\Plex\Plex Media Server\Resources\Plug-ins-186bae04e\Framework.bundle\Contents\Resources\Versions\2\Python\Framework\code\sandbox.py", line 333, in import
return mod.load_module(_name)

File "C:\Program Files (x86)\Plex\Plex Media Server\Resources\Plug-ins-186bae04e\Framework.bundle\Contents\Resources\Versions\2\Python\Framework\code\sandbox.py", line 44, in load_module
module = RestrictedModule(name, path, sandbox)

File "C:\Program Files (x86)\Plex\Plex Media Server\Resources\Plug-ins-186bae04e\Framework.bundle\Contents\Resources\Versions\2\Python\Framework\code\loader.py", line 30, in init
exec(code) in self.dict

File "C:\Users\jphud\AppData\Local\Plex Media Server\Plug-ins\GEVI.bundle\Contents\Code\utils.py", line 17, in
from translate import Translator

File "C:\Program Files (x86)\Plex\Plex Media Server\Resources\Plug-ins-186bae04e\Framework.bundle\Contents\Resources\Versions\2\Python\Framework\code\sandbox.py", line 345, in import
raise e

ImportError: cannot import name request
`

Please help! It is failing on this line
from translate import Translator

Autodetect doesn't work.

I tried to use autodetect in both command-line and in the module. In both the instances, I get an error like this:

"'' IS AN INVALID SOURCE LANGUAGE . EXAMPLE: LANGPAIR=EN|IT USING 2 LETTER ISO OR RFC3066 LIKE ZH-CN. ALMOST ALL LANGUAGES SUPPORTED BUT SOME MAY HAVE NO CONTENT"

Python version: 3.9.4
Translate module version: 3.5.0

Thank you.

Apostrophes are printed as special caracters (FR)

Hello :)

First of all what a great module really !!! The default translator is awesome for basic usage (so is mine)
I just had one small disappointment about the apostrophes printed as special caracters when trying to translate in french

(gl) guillaume@A320MA:~$ translate-cli -t fr "That's his fault not mine"

Translation: C&#39;est sa faute pas la mienne
-------------------------
Translated by: MyMemory

I thought this could have something to do with the terminal's encoding so I tried in pure python3/utf-8 and got the same result

>>> translator= Translator(to_lang="fr")
>>> translation = translator.translate("That's cool isn't it ?")
>>> print(translation)
C&#39;est cool non ?

It's very surprising to me since even mandarin seems to print properly

I was using translate, version 3.5.0 on Ubuntu x86 LTS20 with python 3.7.1 (anaconda)

For now I can use a small hotfix (a simple ".replace("'","'") should do) but maybe it could be fixed idk ? :)

Thanks again for the good work however 👍

translation cut off

Hi, thank you for developing translate.
I tried it and it's very easy to install and use.

import translate
tr = translate.Translator(to_lang='fr')
tr.translate('I am happy that you are a boy.')
'Je suis content que tu sois'

The actual translation should be (and is on the Web version):

'Je suis content que tu sois un garçon.'

I wonder if there is any length limit or an option to get the full sentence. Thank you!

Need to encode input as utf-8

translate does not convert input as from unicode objects, requiring this internally necessary conversion from callers. Consider this example:

> translator= Translator(from_lang="de", to_lang="en")
> print translator.translate(u"Gährung".encode('utf-8'))
fermentation
> print translator.translate(u"Gährung")
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-17-da241bc6d586> in <module>()
----> 1 print translator.translate(u"Gährung")

translate-0.0.6-py2.7.egg/translate.pyc in translate(self, source)
     41     def translate(self, source):
     42         self.source_list = wrap(source, 1000, replace_whitespace=False)
---> 43         return ' '.join(self._get_translation_from_google(s) for s in self.source_list)
     44 
     45     def _get_translation_from_google(self, source):

translate-0.0.6-py2.7.egg/translate.pyc in <genexpr>((s,))
     41     def translate(self, source):
     42         self.source_list = wrap(source, 1000, replace_whitespace=False)
---> 43         return ' '.join(self._get_translation_from_google(s) for s in self.source_list)
     44 
     45     def _get_translation_from_google(self, source):

translate-0.0.6-py2.7.egg/translate.pyc in _get_translation_from_google(self, source)
     44 
     45     def _get_translation_from_google(self, source):
---> 46         json5 = self._get_json5_from_google(source)
     47         return self._unescape(self._get_translation_from_json5(json5))
     48 

translate-0.0.6-py2.7.egg/translate.pyc in _get_json5_from_google(self, source)
     59 
     60     def _get_json5_from_google(self, source):
---> 61         escaped_source = quote(source, '')
     62         headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.168 Safari/535.19'}
     63         req = request.Request(

/usr/lib64/python2.7/urllib.pyc in quote(s, safe)
   1280     if not s.rstrip(safe):
   1281         return s
-> 1282     return ''.join(map(quoter, s))
   1283 
   1284 def quote_plus(s, safe=''):

KeyError: u'\xe4'

Example in README doesn't work

After installing from source:

(env) $ translate-cli -t zh "This is a pen."

Translation: '' IS AN INVALID SOURCE LANGUAGE . EXAMPLE: LANGPAIR=EN|IT USING 2 LETTER ISO OR RFC3066 LIKE ZH-CN. ALMOST ALL LANGUAGES SUPPORTED BUT SOME MAY HAVE NO CONTENT

translate-cli -f es -t zh "This is a pen." works though.

Limits in usage?

Do you have some limits in translation, for example per day or no more than 5000 characters in one translate sentence?

raise JSONDecodeError("Expecting value", s, err.value) from None

Attempted to mimic the example and ran into the following error:

from translate import Translator
translator= Translator(to_lang="zh")
translation = translator.translate("This is a pen.")

[Traceback (most recent call last):

File "", line 3, in
translation = translator.translate("This is a pen.")

File "C:\ProgramData\Anaconda3\lib\site-packages\translate\translate.py", line 42, in translate
return ' '.join(self.provider.get_translation(text_wraped) for text_wraped in text_list)

File "C:\ProgramData\Anaconda3\lib\site-packages\translate\translate.py", line 42, in
return ' '.join(self.provider.get_translation(text_wraped) for text_wraped in text_list)

File "C:\ProgramData\Anaconda3\lib\site-packages\translate\providers\mymemory_translated.py", line 42, in get_translation
data = self._make_request(text)

File "C:\ProgramData\Anaconda3\lib\site-packages\translate\providers\mymemory_translated.py", line 39, in _make_request
return response.json()

File "C:\ProgramData\Anaconda3\lib\site-packages\requests\models.py", line 896, in json
return complexjson.loads(self.text, **kwargs)

File "C:\ProgramData\Anaconda3\lib\json_init_.py", line 348, in loads
return _default_decoder.decode(s)

File "C:\ProgramData\Anaconda3\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())

File "C:\ProgramData\Anaconda3\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None

JSONDecodeError: Expecting value](url)

auto-detect doesn't work when translating from zh_CN to en

Awesome Job ! This project really helps me a lot ! But maybe there is a small issue about language auto-detect when translating from zh_CN to en.

Based on the document , if you want to translate a sentence from en to zh_CN , you just need to use three lines:

In [1]: from translate import Translator
In [2]: translator= Translator(to_lang="zh")
In [3]: translation = translator.translate("This is a pen.")
Out [3]: 这是一支笔

So based on my understanding , if you want to implement the reversed action, you also need three lines:

In [1]: from translate import Translator
In [2]: translator= Translator(to_lang="en")
In [3]: translation = translator.translate("这是一支笔")
Out [3]: 这是一支笔 # Still the original sentence. translation doesn't work

But if you specify the input language,it will work:

In [1]: from translate import Translator
In [2]: translator= Translator(from_lang="zh_CN",to_lang="en")
In [3]: translation = translator.translate("这是一支笔")
Out [3]: This is a pen # Translate successfully

Below is the screenshot tested on python3.5:

image

Bad translation depending on uppercase or not

Hello,

any idea why:

from translate import Translator
text = 'Happy new year'
translator= Translator(to_lang='fr')
translated_text=translator.translate(text)
print(translated_text.encode('utf-8')) 

gives the correct answer (but in uppercase, why?) : 

BONNE ANNÉE
but the same code with

text = 'Happy New Year'
outputs

Bonne Année,La
which doesn't mean anything?

Email

add a valid email adress to get 10 times more translations a day with &de=%s

I created a azure translator on the azure portal and I have the api keys. But I get an error when entering the key in the code.

I entered my first api key in the code below:

from translate import Translator as trans
translator = trans(provider='microsoft', to_lang='nl', secret_access_key='xxxxxx')
translation = translator.translate("I am such an amateur in python, I don't even know how to translate this ")
print(translation)

but then I get the following error:
HTTPError: 401 Client Error: Access Denied for url: https://api.cognitive.microsoft.com/sts/v1.0/issueToken

I replaced my api key with xxxxx, but can anybody explain to me if I entered the right key there?
I took the first key from the 'keys and endpoint' menu in the azure portal.
Or do I have to enter something else here?

UnicodeEncodeError

Whenever I try to run this line of code:-

with open('output.txt', mode='r+') as my_file2:
translator = Translator(to_lang="ja")
translation = translator.translate(a)
my_file2.write(translation)

It shows me:- UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-5: character maps to

you can not change the source text

Hello, my title is somewhat confusing, but I will explain it to you through this code

     from translate import Translator
     translator = Translator(to_lang='en',form_lang ='es')
     texto = input("> ")
     traduccion = translator.translate(texto)
     print(traduccion)

the form_lang ='es', Can you change the source language? I've tried but it does not seem to work

Translation to English

When I try to translate something to English it always responds with the original text and not the translated one.

Example:

In [1]: from translate import Translator
In [2]: translator= Translator(to_lang="en")
In [3]: translation = translator.translate("Waar bevindt zich het dichtbijzijnste treinstation?")
Out [3]: Waar bevindt zich het dichtbijzijnste treinstation?

emoji 💡 can not decode

def transE2C(word):
    translator = Translator(service_urls=[
      'translate.google.com',
      'translate.google.cn',
    ])
    translator = Translator()
    a=translator.translate(word, src='auto' ,dest='zh-cn')
    print(a.text)
    return a.text


transE2C("💡 hi im ok")

Can not install on a windows 10 environment

I need some serious help. Im on the verge of punching my computer screen.

I am getting this error message (see screenshot)
image

I have tried this in pycharm and vscode, neither work and both give same results.

When I am inside the pipenv shell environment for the project within the project folder, I can do pip3 install translate, it provides the error in the screenshot. Same with the terminal and python console in both Vscode and pycharm

I have installed visual studio (per the error instructions) and im getting nowhere.

Error Block

(test-ol2do7ia) (test) C:\Users\Robert\Desktop\Side Projects\Udemy\Master python zero to Mastery\projects\test>pip3 install translate
Collecting translate
  Using cached https://files.pythonhosted.org/packages/85/b2/2ea329a07bbc0c7227eef84ca89ffd6895e7ec237d6c0b26574d56103e53/translate-3.5.0-py2.py3-none-any.whl
Requirement already satisfied: pre-commit in c:\users\robert\.virtualenvs\test\lib\site-packages (from translate) (2.0.1)
Collecting tox (from translate)
  Using cached https://files.pythonhosted.org/packages/3a/21/aa738f33db84be2caf89fae9d868320f7fc004329dd681cec4056d08cf75/tox-3.14.5-py2.py3-none-any.whl
Collecting lxml (from translate)
  Using cached https://files.pythonhosted.org/packages/39/2b/0a66d5436f237aff76b91e68b4d8c041d145ad0a2cdeefe2c42f76ba2857/lxml-4.5.0.tar.gz
Requirement already satisfied: requests in c:\users\robert\.virtualenvs\test\lib\site-packages (from translate) (2.22.0)
Requirement already satisfied: click in c:\users\robert\.virtualenvs\test\lib\site-packages (from translate) (7.0)
Requirement already satisfied: cfgv>=2.0.0 in c:\users\robert\.virtualenvs\test\lib\site-packages (from pre-commit->translate) (3.0.0)
Requirement already satisfied: nodeenv>=0.11.1 in c:\users\robert\.virtualenvs\test\lib\site-packages (from pre-commit->translate) (1.3.5)
Requirement already satisfied: aspy.yaml in c:\users\robert\.virtualenvs\test\lib\site-packages (from pre-commit->translate) (1.3.0)
Requirement already satisfied: identify>=1.0.0 in c:\users\robert\.virtualenvs\test\lib\site-packages (from pre-commit->translate) (1.4.11)
Requirement already satisfied: virtualenv>=15.2 in c:\users\robert\.virtualenvs\test\lib\site-packages (from pre-commit->translate) (20.0.4)
Requirement already satisfied: pyyaml in c:\users\robert\.virtualenvs\test\lib\site-packages (from pre-commit->translate) (5.3)
Requirement already satisfied: toml in c:\users\robert\.virtualenvs\test\lib\site-packages (from pre-commit->translate) (0.10.0)
Collecting colorama>=0.4.1; platform_system == "Windows" (from tox->translate)
  Using cached https://files.pythonhosted.org/packages/c9/dc/45cdef1b4d119eb96316b3117e6d5708a08029992b2fee2c143c7a0a5cc5/colorama-0.4.3-py2.py3-none-any.whl
Collecting py<2,>=1.4.17 (from tox->translate)
  Using cached https://files.pythonhosted.org/packages/99/8d/21e1767c009211a62a8e3067280bfce76e89c9f876180308515942304d2d/py-1.8.1-py2.py3-none-any.whl
Collecting packaging>=14 (from tox->translate)
  Using cached https://files.pythonhosted.org/packages/98/42/87c585dd3b113c775e65fd6b8d9d0a43abe1819c471d7af702d4e01e9b20/packaging-20.1-py2.py3-none-any.whl
Requirement already satisfied: six<2,>=1.14.0 in c:\users\robert\.virtualenvs\test\lib\site-packages (from tox->translate) (1.14.0)
Requirement already satisfied: filelock<4,>=3.0.0 in c:\users\robert\.virtualenvs\test\lib\site-packages (from tox->translate) (3.0.12)
Collecting pluggy<1,>=0.12.0 (from tox->translate)
  Using cached https://files.pythonhosted.org/packages/a0/28/85c7aa31b80d150b772fbe4a229487bc6644da9ccb7e427dd8cc60cb8a62/pluggy-0.13.1-py2.py3-none-any.whl
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in c:\users\robert\.virtualenvs\test\lib\site-packages (from requests->translate) (1.25.8)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in c:\users\robert\.virtualenvs\test\lib\site-packages (from requests->translate) (3.0.4)
Requirement already satisfied: idna<2.9,>=2.5 in c:\users\robert\.virtualenvs\test\lib\site-packages (from requests->translate) (2.8)
Requirement already satisfied: certifi>=2017.4.17 in c:\users\robert\.virtualenvs\test\lib\site-packages (from requests->translate) (2019.11.28)
Requirement already satisfied: appdirs<2,>=1.4.3 in c:\users\robert\.virtualenvs\test\lib\site-packages (from virtualenv>=15.2->pre-commit->translate) (1.4.3)
Requirement already satisfied: distlib<1,>=0.3.0 in c:\users\robert\.virtualenvs\test\lib\site-packages (from virtualenv>=15.2->pre-commit->translate) (0.3.0)
Collecting pyparsing>=2.0.2 (from packaging>=14->tox->translate)
  Using cached https://files.pythonhosted.org/packages/5d/bc/1e58593167fade7b544bfe9502a26dc860940a79ab306e651e7f13be68c2/pyparsing-2.4.6-py2.py3-none-any.whl
Installing collected packages: colorama, py, pyparsing, packaging, pluggy, tox, lxml, translate
  Running setup.py install for lxml ... error
    Complete output from command C:\Users\Robert\.virtualenvs\test\Scripts\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Robert\\AppData\\Local\\Temp\\pip-install-kxiufpya\\lxml\\setup.py';f=getattr(tokenize, 'open', open)
(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\Robert\AppData\Local\Temp\pip-record-t8dsz_vq\install-record.txt --single-version-externally-managed --compile --install-
headers C:\Users\Robert\.virtualenvs\test\include\site\python3.8\lxml:
    Building lxml version 4.5.0.
    Building without Cython.
    ERROR: b"'xslt-config' is not recognized as an internal or external command,\r\noperable program or batch file.\r\n"
    ** make sure the development packages of libxml2 and libxslt are installed **

    Using build configuration of libxslt
    running install
    running build
    running build_py
    creating build
    creating build\lib.win-amd64-3.8
    creating build\lib.win-amd64-3.8\lxml
    copying src\lxml\builder.py -> build\lib.win-amd64-3.8\lxml
    copying src\lxml\cssselect.py -> build\lib.win-amd64-3.8\lxml
    copying src\lxml\doctestcompare.py -> build\lib.win-amd64-3.8\lxml
    copying src\lxml\ElementInclude.py -> build\lib.win-amd64-3.8\lxml
    copying src\lxml\pyclasslookup.py -> build\lib.win-amd64-3.8\lxml
    copying src\lxml\sax.py -> build\lib.win-amd64-3.8\lxml
    copying src\lxml\usedoctest.py -> build\lib.win-amd64-3.8\lxml
    copying src\lxml\_elementpath.py -> build\lib.win-amd64-3.8\lxml
    copying src\lxml\__init__.py -> build\lib.win-amd64-3.8\lxml
    creating build\lib.win-amd64-3.8\lxml\includes
    copying src\lxml\includes\__init__.py -> build\lib.win-amd64-3.8\lxml\includes
    creating build\lib.win-amd64-3.8\lxml\html
    copying src\lxml\html\builder.py -> build\lib.win-amd64-3.8\lxml\html
    copying src\lxml\html\clean.py -> build\lib.win-amd64-3.8\lxml\html
    copying src\lxml\html\defs.py -> build\lib.win-amd64-3.8\lxml\html
    copying src\lxml\html\diff.py -> build\lib.win-amd64-3.8\lxml\html
    copying src\lxml\html\ElementSoup.py -> build\lib.win-amd64-3.8\lxml\html
    copying src\lxml\html\formfill.py -> build\lib.win-amd64-3.8\lxml\html
    copying src\lxml\html\html5parser.py -> build\lib.win-amd64-3.8\lxml\html
    copying src\lxml\html\soupparser.py -> build\lib.win-amd64-3.8\lxml\html
    copying src\lxml\html\usedoctest.py -> build\lib.win-amd64-3.8\lxml\html
    copying src\lxml\html\_diffcommand.py -> build\lib.win-amd64-3.8\lxml\html
    copying src\lxml\html\_html5builder.py -> build\lib.win-amd64-3.8\lxml\html
    copying src\lxml\html\_setmixin.py -> build\lib.win-amd64-3.8\lxml\html
    copying src\lxml\html\__init__.py -> build\lib.win-amd64-3.8\lxml\html
    creating build\lib.win-amd64-3.8\lxml\isoschematron
    copying src\lxml\isoschematron\__init__.py -> build\lib.win-amd64-3.8\lxml\isoschematron
    copying src\lxml\etree.h -> build\lib.win-amd64-3.8\lxml
    copying src\lxml\etree_api.h -> build\lib.win-amd64-3.8\lxml
    copying src\lxml\lxml.etree.h -> build\lib.win-amd64-3.8\lxml
    copying src\lxml\lxml.etree_api.h -> build\lib.win-amd64-3.8\lxml
    copying src\lxml\includes\c14n.pxd -> build\lib.win-amd64-3.8\lxml\includes
    copying src\lxml\includes\config.pxd -> build\lib.win-amd64-3.8\lxml\includes
    copying src\lxml\includes\dtdvalid.pxd -> build\lib.win-amd64-3.8\lxml\includes
    copying src\lxml\includes\etreepublic.pxd -> build\lib.win-amd64-3.8\lxml\includes
    copying src\lxml\includes\htmlparser.pxd -> build\lib.win-amd64-3.8\lxml\includes
    copying src\lxml\includes\relaxng.pxd -> build\lib.win-amd64-3.8\lxml\includes
    copying src\lxml\includes\schematron.pxd -> build\lib.win-amd64-3.8\lxml\includes
    copying src\lxml\includes\tree.pxd -> build\lib.win-amd64-3.8\lxml\includes
    copying src\lxml\includes\uri.pxd -> build\lib.win-amd64-3.8\lxml\includes
    copying src\lxml\includes\xinclude.pxd -> build\lib.win-amd64-3.8\lxml\includes
    copying src\lxml\includes\xmlerror.pxd -> build\lib.win-amd64-3.8\lxml\includes
    copying src\lxml\includes\xmlparser.pxd -> build\lib.win-amd64-3.8\lxml\includes
    copying src\lxml\includes\xmlschema.pxd -> build\lib.win-amd64-3.8\lxml\includes
    copying src\lxml\includes\xpath.pxd -> build\lib.win-amd64-3.8\lxml\includes
    copying src\lxml\includes\xslt.pxd -> build\lib.win-amd64-3.8\lxml\includes
    copying src\lxml\includes\__init__.pxd -> build\lib.win-amd64-3.8\lxml\includes
    copying src\lxml\includes\etree_defs.h -> build\lib.win-amd64-3.8\lxml\includes
    copying src\lxml\includes\lxml-version.h -> build\lib.win-amd64-3.8\lxml\includes
    creating build\lib.win-amd64-3.8\lxml\isoschematron\resources
    creating build\lib.win-amd64-3.8\lxml\isoschematron\resources\rng
    copying src\lxml\isoschematron\resources\rng\iso-schematron.rng -> build\lib.win-amd64-3.8\lxml\isoschematron\resources\rng
    creating build\lib.win-amd64-3.8\lxml\isoschematron\resources\xsl
    copying src\lxml\isoschematron\resources\xsl\RNG2Schtrn.xsl -> build\lib.win-amd64-3.8\lxml\isoschematron\resources\xsl
    copying src\lxml\isoschematron\resources\xsl\XSD2Schtrn.xsl -> build\lib.win-amd64-3.8\lxml\isoschematron\resources\xsl
    creating build\lib.win-amd64-3.8\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
    copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\iso_abstract_expand.xsl -> build\lib.win-amd64-3.8\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
    copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\iso_dsdl_include.xsl -> build\lib.win-amd64-3.8\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
    copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\iso_schematron_message.xsl -> build\lib.win-amd64-3.8\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
    copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\iso_schematron_skeleton_for_xslt1.xsl -> build\lib.win-amd64-3.8\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
    copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\iso_svrl_for_xslt1.xsl -> build\lib.win-amd64-3.8\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
    copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\readme.txt -> build\lib.win-amd64-3.8\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
    warning: build_py: byte-compiling is disabled, skipping.

    running build_ext
    building 'lxml.etree' extension
    error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/

    ----------------------------------------
Command "C:\Users\Robert\.virtualenvs\test\Scripts\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Robert\\AppData\\Local\\Temp\\pip-install-kxiufpya\\lxml\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read()
.replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\Robert\AppData\Local\Temp\pip-record-t8dsz_vq\install-record.txt --single-version-externally-managed --compile --install-headers C:\Users\Robert\
.virtualenvs\test\include\site\python3.8\lxml" failed with error code 1 in C:\Users\Robert\AppData\Local\Temp\pip-install-kxiufpya\lxml\


Dag

Word "their" have incorrect translation on Russian.

translate does not return unicode object when translating empty string

translate does not return consistent types. Consider:

> from translate import Translator
> translator= Translator(to_lang="zh")
> print type(translator.translate("a"))
<type 'unicode'>
> print type(translator.translate(""))
<type 'str'>

This makes writing code that is future-proof for Python 3 harder than necessary.

Unable to install on mac high sierra

When i run pip install, this is what it returns, tried sudo as well,

Collecting translate
Downloading https://files.pythonhosted.org/packages/85/b2/2ea329a07bbc0c7227eef84ca89ffd6895e7ec237d6c0b26574d56103e53/translate-3.5.0-py2.py3-none-any.whl
Requirement already satisfied (use --upgrade to upgrade): lxml in /opt/anaconda3/lib/python3.8/site-packages (from translate)
Requirement already satisfied (use --upgrade to upgrade): requests in /opt/anaconda3/lib/python3.8/site-packages (from translate)
Collecting tox (from translate)
Downloading https://files.pythonhosted.org/packages/d8/63/2fa635ac1b8a22e960654b07c270dfb53eb873aba261006536de40327b18/tox-3.23.1-py2.py3-none-any.whl (85kB)
100% |████████████████████████████████| 92kB 2.8MB/s
Exception:
Traceback (most recent call last):
File "/opt/anaconda3/lib/python3.8/site-packages/pip/_vendor/pkg_resources/init.py", line 2851, in _dep_map
return self.__dep_map
File "/opt/anaconda3/lib/python3.8/site-packages/pip/_vendor/pkg_resources/init.py", line 2685, in getattr
raise AttributeError(attr)
AttributeError: _DistInfoDistribution__dep_map

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/opt/anaconda3/lib/python3.8/site-packages/pip/basecommand.py", line 209, in main
status = self.run(options, args)
File "/opt/anaconda3/lib/python3.8/site-packages/pip/commands/install.py", line 310, in run
wb.build(autobuilding=True)
File "/opt/anaconda3/lib/python3.8/site-packages/pip/wheel.py", line 748, in build
self.requirement_set.prepare_files(self.finder)
File "/opt/anaconda3/lib/python3.8/site-packages/pip/req/req_set.py", line 356, in prepare_files
discovered_reqs.extend(self._prepare_file(
File "/opt/anaconda3/lib/python3.8/site-packages/pip/req/req_set.py", line 647, in _prepare_file
set(req_to_install.extras) - set(dist.extras)
File "/opt/anaconda3/lib/python3.8/site-packages/pip/_vendor/pkg_resources/init.py", line 2810, in extras
return [dep for dep in self._dep_map if dep]
File "/opt/anaconda3/lib/python3.8/site-packages/pip/_vendor/pkg_resources/init.py", line 2853, in _dep_map
self.__dep_map = self._compute_dependencies()
File "/opt/anaconda3/lib/python3.8/site-packages/pip/_vendor/pkg_resources/init.py", line 2886, in _compute_dependencies
common = frozenset(reqs_for_extra(None))
File "/opt/anaconda3/lib/python3.8/site-packages/pip/_vendor/pkg_resources/init.py", line 2883, in reqs_for_extra
if req.marker_fn(override={'extra':extra}):
File "/opt/anaconda3/lib/python3.8/site-packages/pip/_vendor/_markerlib/markers.py", line 113, in marker_fn
return eval(compiled_marker, environment)
File "", line 1, in
NameError: name 'platform_system' is not defined

requests.exceptions.ConnectionError: HTTPConnectionPool(host='api.mymemory.translated.net', port=80): Max retries exceeded with url: /get?q=the+book+is+on+the+table&langpair=autodetect%7Czh

requests.exceptions.ConnectionError: HTTPConnectionPool(host='api.mymemory.translated.net', port=80): Max retries exceeded with url: /get?q=the+book+is+on+the+table&langpair=autodetect%7Czh (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f37f41795d0>: Failed to establish a new connection: [Errno 111] Connection refused'))

用量限制?

您好,謝謝您分享這麼使用的套件

請問每天是不是有翻譯量限制呢?

謝謝

Translation to en not working

When trying to translate to English, the output is the same as the input (I got the text I entered in the same language)

Supported language codes?

The example code is for chinese
translator= Translator(to_lang="zh")
translation = translator.translate("This is a pen.")

But what are the codes for the other languages?

Thanks

Service unavailable

It seems to don't work anymore. This is the result of running the example in the doc

Traceback (most recent call last):
  File "C:\data\progetti_miei\python\translate\main.py", line 3, in <module>
    translation = translator.translate("This is a pen.")
  File "C:\Python36\lib\site-packages\translate.py", line 38, in translate
    return ' '.join(self._get_translation_from_google(s) for s in self.source_list)
  File "C:\Python36\lib\site-packages\translate.py", line 38, in <genexpr>
    return ' '.join(self._get_translation_from_google(s) for s in self.source_list)
  File "C:\Python36\lib\site-packages\translate.py", line 41, in _get_translation_from_google
    json5 = self._get_json5_from_google(source)
  File "C:\Python36\lib\site-packages\translate.py", line 54, in _get_json5_from_google
    r = request.urlopen(req)
  File "C:\Python36\lib\urllib\request.py", line 223, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Python36\lib\urllib\request.py", line 532, in open
    response = meth(req, response)
  File "C:\Python36\lib\urllib\request.py", line 642, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python36\lib\urllib\request.py", line 570, in error
    return self._call_chain(*args)
  File "C:\Python36\lib\urllib\request.py", line 504, in _call_chain
    result = func(*args)
  File "C:\Python36\lib\urllib\request.py", line 650, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 503: Service Unavailable

"from_lang" is set to "en" in __init__ of Translator class

The

    def __init__(self, to_lang, from_lang='en'):
        self.from_lang = from_lang
        self.to_lang = to_lang

Marks the source language to be english hence failing to autodetect

Changing it to auto makes it "auto detect"

    def __init__(self, to_lang, from_lang='auto'):
        self.from_lang = from_lang
        self.to_lang = to_lang

Crashes on certain unicode inputs

When going from one language output to another, there is something that chokes on the unicode within the library. I've added more print lines to illustrate what is going on better.

translator = Translator(to_lang="ru")
translator2 = Translator(to_lang="en")
translation = translator.translate("Test.")
print translation
translation2 = translator2.translate(translation)
print translation2

What I want to do is take the string "Test", turn it into Russian, then output the Russian translation in English.
Doing this yields this error.

Traceback (most recent call last):
  File "C:\Users\powderblock\Documents\GitHub\PyBad-Translator\BadTranslator.py", line 6, in <module>
    translation2 = translator2.translate(translation)
  File "C:\Users\powderblock\Documents\GitHub\PyBad-Translator\translate.py", line 43, in translate
    return ' '.join(self._get_translation_from_google(s) for s in self.source_list)
  File "C:\Users\powderblock\Documents\GitHub\PyBad-Translator\translate.py", line 43, in <genexpr>
    return ' '.join(self._get_translation_from_google(s) for s in self.source_list)
  File "C:\Users\powderblock\Documents\GitHub\PyBad-Translator\translate.py", line 46, in _get_translation_from_google
    json5 = self._get_json5_from_google(source)
  File "C:\Users\powderblock\Documents\GitHub\PyBad-Translator\translate.py", line 61, in _get_json5_from_google
    escaped_source = quote(source, '')
  File "C:\Python27\lib\urllib.py", line 1268, in quote
    return ''.join(map(quoter, s))
KeyError: u'\u0422'

Is there a more elegant way to do this within the library? Am I missing something that I should be doing?

Autodetection fails

Autodetection seems to fail, even on your example:

$ translate-cli -t zh "This is a pen."

Translation: '' IS AN INVALID SOURCE LANGUAGE . EXAMPLE: LANGPAIR=EN|IT USING 2 LETTER ISO OR RFC3066 LIKE ZH-CN. ALMOST ALL LANGUAGES SUPPORTED BUT SOME MAY HAVE NO CONTENT

-------------------------
Translated by: MyMemory

Also explicitly asking for autodetection fails:

$ translate-cli -f autodetect -t zh "This is a pen."
$ translate-cli -f 'autodetect' -t zh "This is a pen."

It comes up with the same result, for any target language. Only entering a valid language identifier for source language explicitly instead works as expected:

$ translate-cli -f en -t zh "This is a pen."

Translation: 这是一支笔
-------------------------
Translated by: MyMemory

Trying to use a different service provider fails completely:

$ translate-cli -p deepl -f autodetect -t zh "This is a pen."
Traceback (most recent call last):
  File "/home/demo/.local/bin/translate-cli", line 6, in <module>
    from translate.__main__ import cli
  File "/home/demo/.local/lib/python2.7/site-packages/translate/__main__.py", line 6, in <module>
    main()
  File "/home/demo/.local/lib/python2.7/site-packages/click/core.py", line 829, in __call__
    return self.main(*args, **kwargs)
  File "/home/demo/.local/lib/python2.7/site-packages/click/core.py", line 782, in main
    rv = self.invoke(ctx)
  File "/home/demo/.local/lib/python2.7/site-packages/click/core.py", line 1066, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/home/demo/.local/lib/python2.7/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/home/demo/.local/lib/python2.7/site-packages/translate/main.py", line 159, in main
    translator = Translator(**kwargs)
  File "/home/demo/.local/lib/python2.7/site-packages/translate/translate.py", line 25, in __init__
    'Please check providers list bellow: {!r}'.format(self.available_providers)
translate.exceptions.InvalidProviderError: Provider class invalid. Please check providers list bellow: ['microsoft', 'mymemory']

Any idea what could cause all this? Maybe the install errors I encountered could cause it?

$ pip install translate
[...everything fine until:]

Building wheels for collected packages: filelock, scandir
  Running setup.py bdist_wheel for filelock ... error
  Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-snvHIF/filelock/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/pip-wheel-HPe58C --python-tag cp27:
  usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
     or: -c --help [cmd1 cmd2 ...]
     or: -c --help-commands
     or: -c cmd --help
  
  error: invalid command 'bdist_wheel'
  
  ----------------------------------------
  Failed building wheel for filelock
  Running setup.py clean for filelock
  Running setup.py bdist_wheel for scandir ... error
  Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-snvHIF/scandir/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/pip-wheel-8EKBmy --python-tag cp27:
  /usr/lib/python2.7/distutils/extension.py:133: UserWarning: Unknown Extension options: 'optional'
    warnings.warn(msg)
  usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
     or: -c --help [cmd1 cmd2 ...]
     or: -c --help-commands
     or: -c cmd --help
  
  error: invalid command 'bdist_wheel'
  
  ----------------------------------------
  Failed building wheel for scandir
  Running setup.py clean for scandir
Failed to build filelock scandir
Installing collected packages: click, contextlib2, zipp, six, scandir, pathlib2, configparser, importlib-metadata, pyparsing, packaging, filelock, pluggy, appdirs, distlib, typing, singledispatch, importlib-resources, virtualenv, toml, py, tox, cfgv, pyyaml, aspy.yaml, nodeenv, futures, identify, pre-commit, certifi, urllib3, idna, requests, translate
  Running setup.py install for scandir ... done
  Running setup.py install for filelock ... done
Successfully installed appdirs-1.4.4 aspy.yaml-1.3.0 certifi-2020.12.5 cfgv-2.0.1 click-7.1.2 configparser-4.0.2 contextlib2-0.6.0.post1 distlib-0.3.1 filelock-3.0.12 futures-3.3.0 identify-1.6.2 idna-2.10 importlib-metadata-2.1.1 importlib-resources-3.3.1 nodeenv-1.6.0 packaging-20.9 pathlib2-2.3.5 pluggy-0.13.1 pre-commit-1.21.0 py-1.10.0 pyparsing-2.4.7 pyyaml-5.4.1 requests-2.25.1 scandir-1.10.0 singledispatch-3.6.1 six-1.15.0 toml-0.10.2 tox-3.23.0 translate-3.5.0 typing-3.7.4.3 urllib3-1.26.4 virtualenv-20.4.4 zipp-1.2.0

Python 2.7.16
pip 18.1 from /usr/lib/python2.7/dist-packages/pip (python 2.7)

P.S.: Many thanks for this great commandline tool!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.