簡體   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