You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何翻译CSV文件每一行?翻译结果不稳定问题求助

解决CSV行翻译不稳定的问题

问题根源

  • googletrans依赖非官方谷歌翻译接口,谷歌会限制请求频率,频繁请求易被拦截,导致翻译失败
  • 原代码未处理空行、特殊字符,也未应对网络波动引发的请求失败
  • 文件读取未指定编码,可能出现乱码干扰翻译逻辑

修复后的代码

from googletrans import Translator
import time

# 指定编码读取文件,避免乱码
with open("ElectricCarData_Norm.csv", encoding="utf-8") as myfile:
    lines = myfile.readlines()

translator = Translator()
with open("Electric.csv", 'w', encoding="utf-8") as op:
    for idx, line in enumerate(lines):
        # 清理行首尾空白,跳过空行
        line = line.strip()
        if not line:
            op.write('\n')
            continue
        
        try:
            # 每翻译一行后添加延迟,规避请求频率限制
            if idx > 0:
                time.sleep(1)
            translation = translator.translate(line, src='en', dest='hi').text
            op.write(f"{translation}\n")
        except Exception as e:
            # 捕获异常,记录失败行,避免程序中断
            print(f"第{idx+1}行翻译失败: {str(e)}")
            # 保留原行或标记失败状态
            op.write(f"[翻译失败]{line}\n")

额外优化建议

  • 若翻译数据量较大,改用谷歌翻译官方API(需付费),稳定性与请求速率更有保障
  • 采用批量翻译模式:将多行内容打包为一个请求,减少总请求次数
  • 用csv模块标准处理CSV文件,避免手动读取行时破坏含换行符的单元格格式

内容的提问来源于stack exchange,提问作者Mansi Kargutkar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 20:33:22