HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

A translator class in Python

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
classpythontranslator

Problem

This class can be used to access the Google Translate web interface and get translation result for large text (split up into sentences).

The Signal class is copied from here.

```
#!/usr/bin/env python3

import urllib.request
import urllib.parse
import re
import traceback
from multiprocessing.dummy import Pool
from bs4 import BeautifulSoup

class Signal:
def __init__(self):
"""
:type self: Signal
:return:
"""
self.__subscribers = []
""":type: list of [function]"""
def emit(self, *args, **kwargs):
for sub in self.__subscribers:
sub(*args, **kwargs)
def connect(self, func):
self.__subscribers.append(func)
def disconnect(self, func):
try:
self.__subscribers.remove(func)
except ValueError:
print("Warning: function %s not removed from signal %s" % (func, self))

# signal = Signal()
# def callback():
# print("Calling back...")
# signal.connect(callback)
# signal.emit()

class Translator(Signal):
allowed_lang = ("nl", "fr", "de", "en")
def __init__(self, from_lang, to_lang, orig_str = None, filename = None):
"""
A translation class for accessing google translate
:type self: Translator
:type from_lang: str
:type to_lang: str
:type orig_str: str
:type filename: str
:param from_lang:
:param to_lang:
:param orig_str:
:param filename:
:return:
"""
super().__init__()
self.connect(self.report)

self._from_lang = from_lang
self._to_lang = to_lang
self.agent = {'User-Agent': "Mozilla/4.0"}
self.linkroot = "http://translate.google.com/m?sl=%s&hl=%s&q=" % (self.from_lang, self.to_lang)

if orig_str != None:
self.orig_str = str(orig_str)
elif filename != None:
with open(filename) as fh:
self.orig_str = fh.read()
else:

Solution

PEP8

Please follow PEP8, the official style guide of Python.

In parameter lists, don't put spaces around = like this:

def __init__(self, from_lang, to_lang, orig_str = None, filename = None):


Write like this:

def __init__(self, from_lang, to_lang, orig_str=None, filename=None):


Put one blank line before method definitions inside a class.
Instead of this:

class Translator(Signal):
    allowed_lang = ("nl", "fr", "de", "en")    
    def __init__(self, from_lang, to_lang, orig_str=None, filename=None):


Write like this:

class Translator(Signal):
    allowed_lang = ("nl", "fr", "de", "en")    

    def __init__(self, from_lang, to_lang, orig_str=None, filename=None):


Don't use != or == when comparing with None like this:

if filename != None:


Write like this:

if filename is not None:


Actually, since filename is supposed to be a string,
this would be the most natural way to write this condition:

if filename:


Avoid using bare except clauses like this as much as possible:

except:
        res = "Failed to fetch translation from google."


This is somewhat better:

except Exception:
        res = "Failed to fetch translation from google."


But it's best to use as specific exception type as possible.

In this code:

def translate(self):
    """
    Parallelization using multiprocessing
    :return:
    """
    pool = multiprocessing.Pool()
    self.trans_str = pool.map(self.translate_sentence, self.orig_str)


It's not recommended to define attributes outside of __init__.
It would be better to initialize the value in the constructor.

It's strange that the docstring says:

:type orig_str: str


But then you have this logic:

if orig_str is not None:
        self.orig_str = str(orig_str)


If the parameter is supposed to be a string,
then you can simply do this:

if orig_str:
        self.orig_str = orig_str

Code Snippets

def __init__(self, from_lang, to_lang, orig_str = None, filename = None):
def __init__(self, from_lang, to_lang, orig_str=None, filename=None):
class Translator(Signal):
    allowed_lang = ("nl", "fr", "de", "en")    
    def __init__(self, from_lang, to_lang, orig_str=None, filename=None):
class Translator(Signal):
    allowed_lang = ("nl", "fr", "de", "en")    

    def __init__(self, from_lang, to_lang, orig_str=None, filename=None):
if filename != None:

Context

StackExchange Code Review Q#73548, answer score: 4

Revisions (0)

No revisions yet.