首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >TypeError:函数python中的“type”对象不可订阅

TypeError:函数python中的“type”对象不可订阅
EN

Stack Overflow用户
提问于 2022-07-06 13:50:23
回答 1查看 638关注 0票数 0

我试图运行以下代码,它在字典的特定值中对关键字进行计数,但它总是将TypeError: 'type' object is not subscriptable显示为代码中的错误。有谁能帮我解决这个问题吗?谢谢

代码语言:javascript
运行
复制
from collections import Counter
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)
    }
// TypeError: 'type' object is not subscriptable

def main() -> None:
    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 |= get_keyword_counts(policy['Text'], keywords)
    print(json.dumps(data, indent=4))


if __name__ == '__main__':
    main()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-06 14:01:53

如果您正在定义参数类型,那么不要直接使用listdict,而是使用typing模块中的ListDict

代码语言:javascript
运行
复制
from typing import List, Dict

def get_keyword_counts(text: str, keywords: List[str]) -> Dict[str, int]:
    ...
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72884764

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档