在字典中迭代与文件名中前5个数字匹配的值

问题描述 投票:0回答:1

我正在尝试根据有关存储在json字典中的文件的信息来重命名某些文件。文件名当前类似于“ 00016_930831_fa.png”。我有关于字典中存储的所有文件的信息,包括名称的“事实”(将为“ 00016_930831_fa_a”)和性别的“个人事实”(将为“男性”或“女性”) )。

json文件看起来像这样,其中包含有关文件的事实:{'images':[{'facts':[{'relative':'data / images / 00001 / 00001_930831_fa_a.ppm.bz2','disc':'1','pitch':'0','nose_coordinates': '268','subject':'cfrS00001','compression':'bzip2','yaw':'0','right_eye_coordinates':'202','environment':'cfrE00001','mouth_coordinates':'266 ','sensor':'cfrN00002','roll':'0','beard':'No','format':'ppm','pose':'fa','collection':'cfrC00001', 'illuminant':'cfrI00001','capture_time':'00:00:00','stage':'cfrT00001','capture_date':'08 / 31/1993','recording':'cfrR00002','天气':'inside','left_eye_coordinates':'326','expression':'fa','mustache':'No','glasses':'Yes'},'base':'00001_930831_fa_a'},'person_facts ':[{'gender':'Male','race':'White','id':'cfrS00001','yob':'1943'},'root':'... data','name ':'00001'},

...但这只是一个图像的数据,有数百个图像。

对于我要重命名的每个文件(在下面的代码中称为'qualified_images',我想通过字典查找与该文件相关联的性别,然后我想添加一个M(如果是男性)或一个F(如果是女性)到文件名的开头。

到目前为止,这是我的代码


data = json.load(open('data.json'))
# the data is in the form of the json shown above.

# choosing, and making a list of, the neutral expression files that we want to search the disctionary for

from os import listdir

directory = '...'

qualified_people = list(fname for fname in listdir(directory) if fname.endswith('.png'))
#this is a list of about 100 photos, where their filenames and information are also stored in the json dictionary

# iterate through dictionary - if it finds an image that matches the name of a file on the qualified_people list , then look at the gender and change the filename accordingly
for gender in data:
    if qualified_people == name in data: #'name' is one of the keys 
        if gender == female; #'gender' is one of the keys
            append qualified_people with F
        else
            append qualified_people with M ```
python json loops dictionary
1个回答
0
投票
#solution for dict if gender is a value
for gender in data:
    if data[gender] in qualified_list: 
        data[gender] = 'male_your_filename' #here renaming happens, whatever suits you best  
        qualified_list.append(data[gender])

我仍然不确定那不是您要找的东西,但是我想是吗?

© www.soinside.com 2019 - 2024. All rights reserved.