Search code examples
pythonjsongoogle-translategoogle-translation-apigoogletrans

How to resolve "TypeError: the JSON object must be str, bytes or bytearray, not NoneType" error, while working on translating with googletrans?


How can I resolve TypeError while translating with googletrans? TypeError occurs on 'result = translator.translate(messages[i], dest='en')', and I can't understand because type of result is 'googletrans.models.Translated'.

I used a colab. Also I made a folder named 'translation' and text files(0.txt, 1.txt...) in 'content' folder.

This is my code:

!pip install googletrans==4.0.0rc1
import os

from googletrans import Translator
translator = Translator(service_urls=[
      'translate.google.com',
      'translate.google.co.kr',
])

messages = []
DATA_PATH = '/content/'

for i in range(100):
  file = open(f'{DATA_PATH}{i}.txt', "r")

  msg = [l.strip('\\n') for l in file.readlines()]
  messages.append(' '.join(msg))

for i in range(100):
  result = translator.translate(messages[i], dest='en')

  file_path = os.path.join("translation", f"{i}.txt")
  with open(file_path, "w") as file:
        file.write(result.text)

Solution

  • The issue is one of the text files in your directory is empty. Because of this the messages variable is an empty string and you receive the error from the translator class.

    A way you can solve this is to find the empty strings and add a message to it. For example one method you can use is:

    messages = []
    
    
    for i in range(100):
      file = open(f'{DATA_PATH}{i}.txt', "r")
      msg = [l.strip('\\n') for l in file.readlines()]
      messages.append(' '.join(msg))
    
    for idx,message in enumerate(messages):
      if message == '':
        messages[idx] = 'Empty'