deftranslate_po_file(input_file, output_file, from_lang, to_lang, appid, appkey): # Set Baidu translation API endpoint endpoint = 'http://api.fanyi.baidu.com/api/trans/vip/translate' # Generate salt for request salt = random.randint(32768, 65536) # Open input and output files withopen(input_file, 'r', encoding='utf-8') as fin, open(output_file, 'w', encoding='utf-8') as fout: # Get total number of lines in the input file total_lines = sum(1for line in fin) fin.seek(0) # Reset file pointer to beginning for line in tqdm(fin, total=total_lines, desc='Translating'): # 使用 tqdm 包装循环 # Clean and prepare the line for translation line = line.strip() # Generate sign for the request sign = make_md5(appid + line + str(salt) + appkey) # Build the translation request payload payload = { 'appid': appid, 'q': line, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign } # Send translation request response = requests.post(endpoint, params=payload) translation_result = response.json() # Extract translated text from the response translated_text = translation_result.get('trans_result', [{}])[0].get('dst', line) # Write translated text to the output file fout.write(f'{translated_text}\n')