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

Google Colab中Python3.7运行Python3.9代码报错如何解决

报错根因
  • Python 3.7 不支持 PEP 585 标准的内置类型泛型写法,直接写list[str]、dict[str, int]这类类型注解就会触发TypeError: 'type' object is not subscriptable报错,该语法是Python 3.9才正式上线的特性。
  • 代码中使用的字典原地合并运算符|=同样是Python 3.9新增的字典语法,3.7版本的字典对象未实现该运算符,运行会抛出类型错误。
  • 原代码存在缩进错误:测试用的data字典定义、后续遍历统计逻辑全部错误缩进在get_keyword_counts函数的return语句之后,属于永远不会被执行的死代码。
适配修改点
  • 从typing模块导入List、Dict类型,替换函数定义中不兼容的原生泛型注解写法。
  • 将字典|=合并操作替换为Python 3.7全版本兼容的dict.update()方法,逻辑效果完全一致。
  • 修正代码缩进,将测试执行逻辑移到函数外部,和函数定义保持同级。
适配后可直接运行的完整代码
from collections import Counter
from typing import List, Dict
import json  # Only for pretty printing `data` dictionary.


def get_keyword_counts(text: str, keywords: List[str]) -> Dict[str, int]:
    return {
        word: count for word, count in Counter(text.split()).items()
        if word in set(keywords)
    }


data = {
    "policy": {
        "1": {
            "ID": "ML_0",
            "URL": "www.a.com",
            "Text": "my name is Martin and here is my code"
        },
        "2": {
            "ID": "ML_1",
            "URL": "www.b.com",
            "Text": "my name is Mikal and here is my code"
        }
    }
}
keywords = ['is', 'my']
for policy in data['policy'].values():
    policy.update(get_keyword_counts(policy['Text'], keywords))
print(json.dumps(data, indent=4))
运行说明

代码运行后会保持原逻辑不变,自动给每条政策文本追加对应关键词的出现次数,格式化输出JSON结果,和Python 3.9环境下运行原代码的输出完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 16:27:48