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

Pylint持续在Python脚本首行import语句处报错 求助排查语法问题

Pylint导入段报错根因及修复方案

Pylint在首行import os位置报错,并非导入语句本身存在语法问题,是后续代码存在非法语法导致Python解析器无法正常解析文件,Pylint将错误锚点定位到了文件开头位置。代码存在的具体问题如下:

  • 冗余/错误导入:导入的os、json、six三个模块全程未被使用;from dotenv import dotenv导入写法错误,dotenv库不存在名为dotenv的可导入对象,不需要加载环境变量可直接删除该行,需要使用的话正确导入写法为from dotenv import load_dotenv。
  • 函数重名冲突:法译英逻辑的函数被错误命名为english_to_french,会直接覆盖前面定义的英译法函数,应重命名为french_to_english。
  • f-string非法语法(核心报错原因):两处parent赋值的f-string中,{ferrous-amphora-352613}和{My First Project}既不是已定义变量,也没有加字符串引号,属于非法Python语法。正确写法应引用函数入参project_id和已定义的location变量。
  • 未定义变量引用:第一个英译法函数的请求参数中,contents字段传入了不存在的text变量,应替换为函数入参english_text。
  • 缩进错误:if __name__ == "__main__":判断块被错误缩进放在第二个函数内部,应顶格写在全局作用域。
  • 冗余变量:两个函数中都定义了location = "global"但未被引用,属于无效代码。

修复后完整代码

from google.cloud import translate


def english_to_french(english_text="Hello", project_id="ferrous-amphora-352613"):
    """英译法逻辑"""
    client = translate.TranslationServiceClient()
    location = "global"
    parent = f"projects/{project_id}/locations/{location}"

    response = client.translate_text(
        request={
            "parent": parent,
            "contents": [english_text],
            "mime_type": "text/plain",
            "source_language_code": "en-US",
            "target_language_code": "fr",
        }
    )

    for translation in response.translations:
        print("Translated text: {}".format(translation.translated_text))


def french_to_english(french_text="Bonjour", project_id="ferrous-amphora-352613"):
    """法译英逻辑"""
    client = translate.TranslationServiceClient()
    location = "global"
    parent = f"projects/{project_id}/locations/{location}"

    response = client.translate_text(
        request={
            "parent": parent,
            "contents": [french_text],
            "mime_type": "text/plain",
            "source_language_code": "fr",
            "target_language_code": "en",
        }
    )

    for translation in response.translations:
        print("Translated text: {}".format(translation.translated_text))


if __name__ == "__main__":
    # 可在此处调用测试函数
    pass

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 20:45:36