0

フォルダ構造があり、ルート フォルダのフォルダ名とファイル ツリーの下のファイルに基づいて JSON オブジェクトを作成したいと考えています。ファイル名は次のように適切に構成されています。

objectNNN.xyz

NNN は 001、002 などの数字で、xyz は .png、.jpg、.eps、.mp3 のいずれかです。

フォルダー構造は次のようになります (スクリプトへの入力)。

果物

  • 画像

    • apple001.jpg
    • apple002.jpg
    • apple003.jpg
    • オレンジ001.jpg
    • orange002.png
    • オレンジ003.jpg
    • apple001.mp3
    • apple002.mp3
    • オレンジ001.mp3

動物

  • ...など

食べ物

  • ...など

... この FOLDER 構造に基づいて、すべての「セット」(果物、動物など) を読み取り、以下のように各セットの JSON オブジェクトを作成したいと思います: (「単語」キーはすべてから取得されることに注意してください。 images ディレクトリ内のオブジェクト名)。

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 に答える