【问题标题】:Want to store last paragraph to any variable想要将最后一段存储到任何变量
【发布时间】:2011-11-07 16:27:28
【问题描述】:

我有long text。我正在将此字符串转换为 dict。

这里是代码

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'}

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

【问题讨论】:

  • 您的最后一段没有您期望的key = value 格式...或者,最后一段是否应该具有followed by 的值?
  • 您尝试解析的文本:它是纯文本还是 XML?在您提供的 dpaste 链接上,它的语法是 XML。
  • @sberry2A 最后一段不是后面的值。这是单独的字符串。

标签: python regex dictionary


【解决方案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”中。我使用集合模块中的 defaultdict 开始我的答案,并将值设置为列表,以便您可以跟踪任何未键入的值,但是,如果您的格式是一致的,那么上述应该可以工作。

【讨论】:

    【解决方案2】:

    您没有将文本存储在底部。您为字典条目分配值的唯一位置是 if len(temp) == 2。由于该文本段落没有等号,因此这部分将简单地通过并且不会执行任何操作。你在某处需要一个“其他”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-16
      • 2014-03-30
      • 1970-01-01
      相关资源
      最近更新 更多