0

我有文件夹结构,我想根据根文件夹中的文件夹名称和文件树中的以下文件创建 JSON 对象。文件名结构良好,如下所示:

objectNNN.xyz

其中 NNN 是 001、002 ... 之类的数字,xyz 可以是 .png、.jpg、.eps 或 .mp3

文件夹结构是这样的(脚本的输入):

水果

  • 图片

    • 苹果001.jpg
    • apple002.jpg
    • apple003.jpg
    • 橙色001.jpg
    • 橙色002.png
    • 橙色003.jpg
  • 声音

    • 苹果001.mp3
    • 苹果002.mp3
    • 橙色001.mp3

动物

  • ... ETC

食物

  • ... ETC

...基于此文件夹结构,我想阅读所有“集合”(水果、动物等)并为每个集合创建一个 JSON 对象,如下所示:(请注意,“单词”键取自所有图像目录中的对象名称)。

sets = {
animals: [ // this is from the folder name in the root folder
{
  word: "cat", // this is from the filename in the images directory eg cat001.jpg
  images: [
    {
      path: "images/basic/cat001.jpg"
    }, {
      path: "images/basic/cat002.jpg"
    }
  ],
  sounds: [ // based on all the images look for sounds
    {
      path: "sounds/basic/cat001.mp3"
    }, {
      path: "sounds/basic/cat002.mp3"
    }
  ]
}, // etc more sets and words
4

1 回答 1

2

这个问题的定义相当不明确,但这是我解释你想要什么的最佳方式。将此扩展到添加文件路径和更多项目组作为练习留给读者。

from re import split
from itertools import groupby, izip

fruits = set(["apple", "pear"])
animals = set(["bear", "cat"])

json_structure = {}

text_input = ["apple001.png", "apple002.jpg", "bear001.png", "pear001.png", "cat001.png"]

def check(filename):
"""Checks which group a filename is in and returns an integer for ordering"""
    n = split(r'[0-9]', filename)[0]
    if n in fruits:
        return 0
    else:
        return 1


grouped = groupby(sorted(text_input, key=check), key=check)

for objects, object_type in izip(grouped, ["fruits", "animals"]):
    items = objects[1]
    json_structure[object_type] = list(items)

print json_structure
于 2012-06-25T03:35:12.710 回答