Search code examples
pythongoogle-translate

Test if parameter is with specific value


Is it possible to test with if or other functions that a variable has a specific value passed in a specific argument?

For instance here is a line of code that detects the language of a string of text. I need to perform a test to conclude if the text is in English. This information passed inside the argument lang which would be lang=en in case of English. If lang is not en for variable language I will then perform the translation to English.

The gola is not to translate text that is in English to be more efficient. Or maybe it is more efficient to just let googletrans translate English to English and not perform the test at all? What would be more efficient - to translate from English to English or to perform the check that I intend. I will have to translate many thousands of strings.

from googletrans import Translator

words = ['Many', 'like', 'name', 'kas', 'jauni burti']

translate = Translator()
for language in words:
    print(translate.detect(language))

Result

Detected(lang=en, confidence=1.0)
Detected(lang=en, confidence=1.0)
Detected(lang=en, confidence=0.95300263)
Detected(lang=lv, confidence=0.43629345)
Detected(lang=lv, confidence=1.0)

Solution

  • Testing specific value

    A few notes about terminology:

    • variable ... a "named free object", e.g. words, word or detected below
    • parameter ... function input used in function definition, e.g. text in detect documentation
    • argument ... specific value passed to a function/method, e.g. below word is argument passed to translate.detecct
    • attribute, member ... member variable of a class/instance/object/..., e.g. lang and confidence are attributes of Detected instances.

    OP is asking for parameter, variable and argument, but what is actually wanted is an attribute. Next time please use proper terminology to prevent confusion.

    An example how it could work:

    from googletrans import Translator
    
    words = ['Many', 'like', 'name', 'kas', 'jauni burti']
    
    translate = Translator()
    for word in words:
        detected = translate.detect(word)
        print(detected)
        if detected.lang == "en":
            print("   ","English")
        else:
            print("   ","not English!")
    
    # print(dir(detected))
    

    Note, dir returns all available attributes of passed argument.

    Performance

    According to documentation, googletrans uses Google Translate Ajax API , most likely involving some network operations. So you should measure the performance yourself, preferably on a target system.