(text, target_lang)
| 112 | |
| 113 | # 调用谷歌API进行翻译 |
| 114 | def translate_text(text, target_lang): |
| 115 | # 整个字符串为黑名单中文本,直接返回 |
| 116 | if text in blacklist: |
| 117 | return text |
| 118 | if cache_manager.check_translation(target_lang, text): |
| 119 | cache_text = cache_manager.get_translation(target_lang, text) |
| 120 | return cache_text |
| 121 | # 对文本中含有黑名单的部分进行替换,并临时替换 |
| 122 | forbiddens = [] |
| 123 | c = 0 |
| 124 | for forbidden in blacklist: |
| 125 | if forbidden in text: |
| 126 | c += 1 |
| 127 | replacement = f'2025323_{c}' |
| 128 | forbiddens.append((forbidden, replacement)) |
| 129 | text = text.replace(forbidden, replacement) |
| 130 | # 如果在缓存中,判断布尔值 |
| 131 | if text in encode_map: |
| 132 | cached_translation, needs_api_translation = encode_map[text] |
| 133 | # 如果缓存中的布尔值为 False,直接使用缓存翻译 |
| 134 | if not needs_api_translation: |
| 135 | # print(f"从缓存中获取翻译:{text} -> {cached_translation}") |
| 136 | return cached_translation |
| 137 | # 如果布尔值为 True,强制调用 API 翻译,不使用缓存的翻译 |
| 138 | else: |
| 139 | print(f"{text} 在缓存中,但需要通过 API 翻译。") |
| 140 | # 调用翻译 API 进行翻译 |
| 141 | api_url = 'https://translate.googleapis.com/translate_a/single' |
| 142 | params = {'client': 'gtx', 'dt': 't', 'sl': 'auto', 'tl': target_lang, 'q': text} |
| 143 | full_url = api_url + '?' + urllib.parse.urlencode(params) |
| 144 | try: |
| 145 | # 调用 API 获取翻译 |
| 146 | response = urlopen(full_url) |
| 147 | data = response.read().decode('utf-8') |
| 148 | parsed_data = json.loads(data.replace("'", "\u2019")) |
| 149 | translations = [] |
| 150 | for segment in parsed_data[0]: |
| 151 | if len(segment) > 0: |
| 152 | translations.append(segment[0]) |
| 153 | translated_text = " ".join(translations) |
| 154 | # 如果缓存中该词条的布尔值为 True 进行 URL 编码 |
| 155 | if text in encode_map and encode_map[text][1]: |
| 156 | translated_text = urllib.parse.quote(translated_text) |
| 157 | # 包含黑名单的字符串,需要替换为原来的未翻译结果 |
| 158 | for forbidden, replacement in forbiddens: |
| 159 | translated_text = translated_text.replace(replacement, forbidden) |
| 160 | if not cache_manager.check_translation(target_lang, text): |
| 161 | cache_manager.add_translation(target_lang, text, translated_text) |
| 162 | return translated_text |
| 163 | except Exception as e: |
| 164 | print(f"翻译错误:{e}") |
| 165 | return None |
| 166 | |
| 167 | |
| 168 | # 翻译锁,确保多个线程不会同时修改 translations |
no test coverage detected