【问题标题】:Separate text from nested OrderedDict in Python在 Python 中从嵌套的 OrderedDict 中分离文本
【发布时间】:2014-04-10 14:18:05
【问题描述】:

这是我的OrderedDict 对象,

a=OrderedDict([(u'p', [u'"The Exam Room" is a new series in which everyday medical questions are answered by physicians and professors from the Yale School of Medicine.', u'In our second episode: Dr. Stephen Strittmatter, Vincent Coates Professor of Neurology and director of the Adler Memory Clinic in Neurology, explains when memory loss can become a problem and what you can do to boost your brain power.', OrderedDict([(u'em', u'Produced & Hosted by Noah Golden')])])])

我想要做的是从这个对象中获取文本,

>>> a.get('p')

得到输出,

[u'"The Exam Room" is a new series in which everyday medical questions are answered by physicians and professors from the Yale School of Medicine.', u'In our second episode: Dr. Stephen Strittmatter, Vincent Coates Professor of Neurology and director of the Adler Memory Clinic in Neurology, explains when memory loss can become a problem and what you can do to boost your brain power.', OrderedDict([(u'em', u'Produced & Hosted by Noah Golden')])]

但结果文本也包含一个OrderedDict

如何合并来自 OrderedDict 的文本,

预期输出:

The Exam Room" is a new series in which everyday medical questions are answered by physicians and professors from the Yale School of Medicine.', u'In our second episode: Dr. Stephen Strittmatter, Vincent Coates Professor of Neurology and director of the Adler Memory Clinic in Neurology, explains when memory loss can become a problem and what you can do to boost your brain power. Produced & Hosted by Noah Golden

【问题讨论】:

    标签: python ordereddictionary


    【解决方案1】:

    如果您事先不知道类型的嵌套,这里的关键是递归。这是一个示例(为便于阅读,对文本进行了格式化):

    #!/usr/bin/env python
    
    import collections
    
    a = collections.OrderedDict([(u'p', [u""" 
        "The Exam Room" is a new series in
        which everyday medical questions are answered by physicians and 
        professors from the Yale School of Medicine.""", 
        u"""In our second episode: Dr. Stephen Strittmatter,
        Vincent Coates Professor of Neurology and director of
        the Adler Memory Clinic in Neurology, explains when 
        memory loss can become a problem and what you can do to 
        boost your brain power.""", 
        collections.OrderedDict([(u'em',
            u'Produced & Hosted by Noah Golden')])])])
    

    现在展平对象,可能是映射或列表。实现了三个选项:如果找到的值是一个字符串,我们只需将其附加到我们的collector。如果是listMapping,我们再次调用flatten。请注意,您可以使用 allowed kwarg 指定一些允许的标签:

    def flatten(obj, allowed=(u'p', u'em')):
        collector = []
    
        def process(v, collector=collector):
            if isinstance(v, (list, collections.Mapping)):
                collector += flatten(v, allowed=allowed)
            elif isinstance(v, basestring):
                collector.append(v)
            else:
                raise ValueError('Cannot handle type: {t}'.format(t=v.__class__))
    
        if isinstance(obj, list):
            for v in obj:
                process(v)
    
        if isinstance(obj, collections.Mapping):
            for k, v in obj.iteritems():
                if k in allowed:
                    process(v)
    
        return collector
    
    if __name__ == '__main__':
        print(flatten(a))
    

    您的示例的结果将是一个三元素列表,如下所示:

    [u'"The Exam Room" is a new series ...',
     u'In our second episode: ...',
     u'Produced & Hosted by Noah Golden']
    

    现在,如果您想要一个字符串,只需 join 现在扁平化的列表:

    print(''.join(flatten(a)))
    

    【讨论】:

      【解决方案2】:

      这是一个奇怪的字典,但你可以像这样实现你想要的:

      [a['p'][0],a['p'][1] + u' ' + a['p'][2]['em']]
      

      结果:

      [u'“The Exam Room”是一个新系列,其中包含日常医学问题 由耶鲁大学的医生和教授回答 医学。',你'在我们的第二集中:斯蒂芬·斯特里特马特博士,文森特 Coates 神经病学教授和阿德勒记忆诊所主任 在神经病学中,解释了记忆丧失何时会成为问题以及什么 你可以这样做来提高你的脑力。由诺亚制作和主持 金']

      这将返回一个列表,正如您在问题中所要求的那样。如果您想使用单个字符串:

      import string
      string.join([a['p'][0],a['p'][1],a['p'][2]['em']])
      

      这将导致:

      “The Exam Room”是一个新系列,其中包含日常医学问题 由耶鲁大学的医生和教授回答 药物。在我们的第二集中:斯蒂芬·斯特里特马特博士,文森特 Coates 神经病学教授和阿德勒记忆诊所主任 在神经病学中,解释了记忆丧失何时会成为问题以及什么 你可以这样做来提高你的脑力。由诺亚制作和主持 金色

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-19
        • 2020-07-28
        • 2021-09-27
        • 2021-12-01
        • 2015-04-17
        • 2021-05-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多