【问题标题】:TypeError: the JSON object must be str, bytes or bytearray, not NoneType (while Using googletrans API)TypeError:JSON 对象必须是 str、bytes 或 bytearray,而不是 NoneType(使用 googletrans API 时)
【发布时间】:2022-01-12 13:25:17
【问题描述】:

我正在尝试使用 googletrans API 翻译 yml 文件。 这是我的代码:

#Import
from googletrans import Translator
import re

# API
translator = Translator()

# Counter
counter_DoNotTranslate = 0
counter_Translate = 0

#Translater
with open("ValuesfileNotTranslatedTest.yml") as a_file: #Values file not translated
  for object in a_file:
    stripped_object = object.rstrip()
    found = False
    file = open("ValuesfileTranslated.yml", "a") #Translated file
    if "# Do not translate" in stripped_object: #Dont translate lines with "#"
      counter_DoNotTranslate += 1
      file.writelines(stripped_object + "\n")
    else: #Translates english to dutch and appends
      counter_Translate += 1
      results = translator.translate(stripped_object, src='en', dest='nl')
      translatedText = results.text
      file.writelines(re.split('|=', translatedText, maxsplit=1)[-1].strip() + "\n" )

#Print
print("# Do not translate found: " + str(counter_DoNotTranslate))
print("Words translated: " + str(counter_Translate))

这是我要翻译的yml文件:

'Enter a section title'
'Enter a description of the section. This will also be shown on the course details page'

'Title'
'Description'
'Start date'
'End date'
Published
Section is optional
Close discussions?



'Enter a title'

但是当我尝试运行代码时,出现以下错误:

File "/Users/AndreB/Library/Python/3.9/lib/python/site-packages/googletrans/client.py", line 219, in translate
    parsed = json.loads(data[0][2])
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/__init__.py", line 339, in loads
    raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not NoneType

我认为问题是yml文件中有不同的空格,所以我尝试添加

if stripped_object is None: #This would skip the lines in the yaml file where there are whitespaces
      file.writelines(stripped_object + "\n") 

到代码。但我仍然收到相同的错误消息。

有人知道我该如何解决这个问题吗?

【问题讨论】:

  • 你的 yml 文件在任何意义上都不是 yaml

标签: python yaml google-translation-api


【解决方案1】:

您提供的代码存在很多问题,但没有一个是导致问题的原因。确实,问题可能是由 yml 文件中的空行引起的,但是您的测试不正确:

"" is None # False
" " is None # also False
not "" # True
not " " # False
not " ".strip() # True

因此,测试由零个或多个空格字符组成的行的正确方法是采用line.strip() 的真实性。在这种情况下,您的门将是:

if not line.strip():
    out.write("\n")

这让我想到了这段代码的其他问题:

  • 您的变量名称会影响内部名称(objectfile
  • 尽管在第一种情况下正确使用了上下文管理器,但您打开输入文件中每一行的输出文件(并且永远不会关闭它)
  • 您的变量名混合约定(snake_case 和 camelCase)

下面是一个避免这些问题的函数的草图:

from pathlib import Path
from googletrans import Translator

translator = Translator()

def translate_file(infn: str | Path, outfn: str | Path, src="en", dest="dl") -> Tuple[int, int]:
    inf = Path(infn)
    outf = Path(outfn)
    translated = 0
    skipped = 0
    
    with infn.open() as inf, outfn.open("w") as outf:
        for line in inf:
            if not line.strip():
                outf.write("\n")
            elif "# Do not translate" in line:
                outf.write(line)
                skipped += 1
            else:
                outf.write(translate.translate(line, src=src, dest=dest))
                translated += 1

    return translated, skipped

您无疑还想做其他事情,我不明白您处理来自translate.translate() 的响应的代码(毫无疑问,因为我从未使用过该库)。

请注意,如果您确实想要翻译真正的 yml,您会好多首先解析它,然后翻译树中需要翻译的位,然后将其转储回磁盘。逐行工作迟早会因无效的语法而中断。

【讨论】:

    猜你喜欢
    • 2019-08-27
    • 1970-01-01
    • 2023-03-13
    • 2017-07-10
    • 1970-01-01
    • 2021-06-17
    • 2022-12-08
    • 1970-01-01
    • 2017-08-11
    相关资源
    最近更新 更多