繁体   English   中英

Python:访问 JSON 元素

[英]Python : Access a JSON element

这是我的 Json 文件的示例:

{ 'data':[{'word':'first_word',
           'vector':[[0.4][0.2][0.8] } ,
          {'word':'second_word',
           'vector':[[0.2][0.65][0.7] }
          ]}

我想访问给定单词及其向量的值,并将其存储在变量中。 这是我所做的:

with open('./Vectors.json') as json_file:
    data_dict = json.loads(json_file)
    for word in words: 
        vector = data_dict["Data"][0][w]["vector"]

它返回给我以下错误:

TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper

你必须使用json.load

json.loads当您的 json 在字符串、字节或字节数组中时使用它

with open('./Vectors.json') as json_file:
    data_dict = json.load(json_file)

您可以使用dict理解对每个单词的向量值使用 map 的字典:

word_vect = {d['word']: d['vector'] for d in data_dict['data']}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM