Python从文本文件形成字典,其值为元组

时间:2015-07-19 11:08:34

标签: python-3.x dictionary

import pickle
def create_dict():



    final_image_dict = {}
    f_name = "./images/image_dict.txt"

    handle = open(f_name, encoding = 'utf-8')
    for line in handle:
        if line.startswith(" ") : continue
        terms = line.split(": ")
        term = terms[0]
        dict_tuple = terms[1].split(",")
        caption = dict_tuple[0]
        image = dict_tuple[1]

        final_image_dict[term] = final_image_dict.get(term, dict_tuple)


    with open("./images/final_image_dict.txt", "wb") as image_infile:
        pickle.dump(final_image_dict, image_infile)

我正在尝试使用上述功能,从以下格式的文本文件中以key:(标题,图像)的格式创建字典:

addugliare:  (Coil a rope = Avvolgere a spire una cima,addugliare.gif),
admiral:  (classic anchor= ancora classico,admiral.gif),
aft:  (verso la poppa, aft.gif),
alberatura: (mastage,alberatura.gif),
albero: (mast = albero, albero.gif),
ancore: (anchors, anchore.gif),
andatu: (tacks, andatu.gif),
armi: (sailing craft, armi.gif),
bearing: (rilevamento , bearing.gif), etc

我的问题是为值创建元组。 上面给出了{'mooring': [' (ormeggio', ' mooring.gif)', '\n'], 'knot(speed)': [' (nodo(velocità)', ' knot.gif)', '\n'], 'addugliare': [' (Coil a rope = Avvolgere a spire una cima', 'addugliare.gif)',而不是'mooring': ('ormeggio','mooring.gif'),这是我想要的格式。请有人帮忙。我也试过(标题,图片)似乎返回了一个对我不起作用的元组元组

1 个答案:

答案 0 :(得分:1)

也许是这样的(修改为忽略空白行和尾随空格):

def extractTuple(s):
    s = s.strip()
    n = len(s)
    p = s[1:n-1].split(',')
    return (p[0].strip(),p[1].strip())

def dictFromFile(fname):
    f = open(fname)
    lines = f.read().split('\n')
    f.close()
    d = {}
    for line in lines:
        line = line.strip()
        if line.endswith(','):
            line = line[:len(line)-1]
            k,v = line.split(':')
            d[k] = extractTuple(v)
    return d

使用您的示例数据:

>>> d = dictFromFile("test.txt")
>>> for k in d: print(k,':',d[k])

admiral : ('classic anchor= ancora classico', 'admiral.gif')
armi : ('sailing craft', 'armi.gif')
addugliare : ('Coil a rope = Avvolgere a spire una cima', 'addugliare.gif')
aft : ('verso la poppa', 'aft.gif')
andatu : ('tacks', 'andatu.gif')
alberatura : ('mastage', 'alberatura.gif')
albero : ('mast = albero', 'albero.gif')
ancore : ('anchors', 'anchore.gif')
bearing : ('rilevamento', 'bearing.gif')