JIT
debugging translation function for specific language issues
下面这个函数。有时候运行不正常显示: translate_zoo_file("es",315) raceback (most recent call last): File "D:\python\1\hello.py", line 68, in <module> translate_zoo_file("es",315) File "D:\python\1\hello.py", line 23, in translate_zoo_file translation = translator.translate(line, src='en', dest=language) File "C:\Users\2\AppData\Local\Programs\Python\Python39\lib\site-packages\googletrans\client.py", line 222, in translate translated_parts = list(map(lambda part: TranslatedPart(part[0], part[1] if len(part) >= 2 else []), parsed[1][0][0][5])) TypeError: 'NoneType' object is not iterable 但是当参数不是es,是de或fr时一切正常。 translate_zoo_file("de",315) translate_zoo_file("fr", 315) 这样就一切正常。 函数如下: def translate_zoo_file(language,number): # 设置代理 os.environ['HTTP_PROXY'] = 'http://127.0.0.1:7897' os.environ['HTTPS_PROXY'] = 'http://127.0.0.1:7897' # 初始化翻译器 translator = Translator() # 读取zoo.txt前number行 with open('zoo.txt', 'r', encoding='utf-8') as f: lines = [line.strip() for line in f.readlines()[:number]] # 翻译 translated_lines = [] for line in lines: if line: # 跳过空行 translation = translator.translate(line, src='en', dest=language) translated_lines.append(translation.text) # 写入de.txt with open(f'{language}.txt', 'w', encoding='utf-8') as f: f.write('\n'.join(translated_lines)) # 删除zoo.txt中的前number行 with open('zoo.txt', 'r', encoding='utf-8') as f: remaining_lines = f.readlines()[number:] with open('zoo.txt', 'w', encoding='utf-8') as f: f.writelines(remaining_lines) print(f"翻译完保存{language}.txt,已从zoo.txt中删除已翻译的{number}行")

The issue occurs because the Google Translate API sometimes returns None for certain languages (like Spanish 'es'). Here's an improved version of the function with error handling:

Updated files
v1