2011-11-07 41 views
0

我有long text。我将这个字符串转换为字典。想将最后一段存入任何变量

这里是代码

data_dict = {}  
filter_dict = {}  
for each in text.split("\n"): 
    temp = each.split('=') 
    if len(temp) == 2: 
     data_dict[temp[0]] = temp[1] 
data = dict((k.strip(), v.strip()) for k, v in data_dict.iteritems()) 

这里的输出是从文本转换为快译通

{'producer': 'Sailadhar Baruah', 
'image': 'paporithefilm.jpg', 
'distributor': '', 
'alt': '', 
'image size': '', 
'gross': '', 
'writer': 'Jahnu Barua', 
'cinematography': 'Binod Pradhan', 
'music': 'Satya Baruah P. P. Vidyanathan', 
'followed by': '', 
'narrator': '', 
'director': 'Jahnu Barua', 
'released': '1986', 
'studio': 'Dolphin s Pvt. Ltd', 
'starring': 'Gopi Desai Biju Phukan Sushil Goswami Chetana Das Dulal Roy', 
'editing': '', 
'name': 'Papori', 
'language': 'Assamese languageAssamese', 
'country': 'Assam, IND', 'budget': '', 
'caption': 'A Screenshot', 
'preceded by': '', 
'runtime': '144 minutes'} 

我只是想知道哪里是我的最后一段到哪里去了?我可以将最后一段文字存储到任何变量吗?谢谢

+1

您的最后一段没有像您所期望的那样的'key = value'格式...或者,是最后一段为'后面跟着的值吗? – sberry

+0

您尝试解析的文本:它是纯文本格式还是XML格式?在您提供的dpaste链接上,它的语法是XML。 – shimofuri

+0

@shimofuri它的纯文本。 –

回答

1

正如已经指出的那样,只有当你有key = value格式时才匹配。试试像这样的东西。

text = file("text.txt", "r").readlines() 

skip_keys = ('film', '') 
data_dict = {} 
for each in text: 
    temp = [x.strip() for x in each.split('=')] 
    if temp[0] in skip_keys: 
     continue 
    if len(temp) == 2: 
     data_dict[temp[0]] = temp[1] 
    else: 
     data_dict['no_key'] = temp[0] 
print data_dict 

在这里,您的段落将被添加到'no_key'。我使用collections模块中的defaultdict开始了我的答案,并将该值设置为列表,以便可以跟踪任何无键值,但是,如果您的格式一致,则上述内容应该可以工作。

1

您没有将文本存储在底部。唯一将值分配给字典条目的地方是在if(len)(temp)== 2之下。由于该文本段落没有等号,所以这部分将简单地通过并且不会做任何事情。你需要一个'其他地方'