2

ここに私の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')])]

しかし、結果のテキストにも one が含まれてい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
4

2 に答える 2

2

事前に型のネストがわからない場合、ここで重要なのは再帰です。以下に例を示します (読みやすいようにテキストをフォーマットしています)。

#!/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')])])])

次に、マッピングまたはリストのオブジェクトをフラット化します。3 つのオプションが実装されています。見つかった値が文字列の場合は、それを に追加するだけcollectorです。alistまたは aの場合は、再度Mapping呼び出しますflattenallowedkwargでいくつかの許可されたタグを指定できることに注意してください。

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))

あなたの例の結果は、次のような 3 つの要素のリストになります。

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

単一の文字列が必要な場合は、joinフラット化されたリストだけです。

print(''.join(flatten(a)))
于 2014-04-10T14:36:21.943 に答える
1

これは奇妙な口述ですが、次のようにして欲しいものを達成できます。

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

結果:

[u'「The Exam Room」は、イェール大学医学部の医師と教授が日常の医学的質問に答える新しいシリーズです。'、u'2 番目のエピソードでは、Vincent Coates の神経学教授である Stephen Strittmatter 博士と、神経学のアドラー記憶クリニックのディレクターが、記憶喪失が問題になる時期と、脳力を高めるためにできることを説明します。ノア・ゴールデンがプロデュース&ホスト

あなたが質問で求めたように、これはリストを返します。代わりに単一の文字列が必要な場合:

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

結果は次のようになります。

「The Exam Room」は、イェール大学医学部の医師や教授が日常の医学的質問に答える新しいシリーズです。2 番目のエピソードでは、Vincent Coates 神経学教授であり、神経学の Adler Memory Clinic のディレクターである Stephen Strittmatter 博士が、記憶喪失が問題になる時期と、脳力を高めるために何ができるかについて説明します。ノア・ゴールデンがプロデュース&ホスト

于 2014-04-10T14:24:23.623 に答える