【发布时间】: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