[Zope3-Users] Static vocabulary

Stephan Richter srichter at cosmos.phy.tufts.edu
Thu Jun 1 16:21:25 EDT 2006


On Sunday 30 April 2006 13:52, Florian Lindner wrote:
> I want to define an vocabulary schema field with a fixed sets of values.
> How can I do that? How can I define it directly in ZCML?

I would not define such thing in ZCML, use Python instead:

from zope.schema import vocabulary

vocab = vocabulary.SimpleVocabulary(
    vocabulary.SimpleTerm('de', title='German'),
    vocabulary.SimpleTerm('en', title='English'),
    ...
)

Alternatively you could create a vocabulary from a CSV file. Here is some code 
I wrote recently:

import csv, os
from zope.schema import vocabulary

def CSVVocabulary(filename):
    # Create a prefix
    prefix = os.path.split(filename)[-1][:-4]
    # Open a file and read the data
    f = file(filename)
    reader = csv.reader(f, delimiter=";")
    # Create the terms and the vocabulary
    terms = []
    for id, title in reader:
        title = unicode(title, 'latin1')
        term = vocabulary.SimpleTerm(id, title=_(prefix+'-'+id,default=title))
        terms.append(term)
    return vocabulary.SimpleVocabulary(terms)

Oh, and if you want to extract those titles for translation, you can use this: 

def csv_strings():
    """Extract message strings from CSV data files"""
    catalog = {}
    datadir = os.path.join(os.path.dirname(__file__), 'data')
    for filename in os.listdir(datadir):
        if filename.endswith('.csv'):
            fullpath = os.path.join(datadir, filename)
            vocab = CSVVocabulary(fullpath)
            for index, term in enumerate(vocab):
                if term.title not in catalog:
                    catalog[term.title] = []
                catalog[term.title].append((fullpath, index+1))
    return catalog

Regards,
Stephan
-- 
Stephan Richter
CBU Physics & Chemistry (B.S.) / Tufts Physics (Ph.D. student)
Web2k - Web Software Design, Development and Training


More information about the Zope3-users mailing list