我试图运行以下代码,它在字典的特定值中对关键字进行计数,但它总是将TypeError: 'type' object is not subscriptable
显示为代码中的错误。有谁能帮我解决这个问题吗?谢谢
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()
发布于 2022-07-06 14:01:53
如果您正在定义参数类型,那么不要直接使用list
或dict
,而是使用typing
模块中的List
或Dict
。
from typing import List, Dict
def get_keyword_counts(text: str, keywords: List[str]) -> Dict[str, int]:
...
https://stackoverflow.com/questions/72884764
复制相似问题