Python正确的解析方法

2024-05-13 19:31:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在编写一个脚本,它将与Youtubes API一起工作。我仍然在学习如何正确地使用Python进行解析,但是对于这样的东西应该采用什么方法有些迷茫。你知道吗

我有这个字符串:

[{'term': u'Video Blogging', 'scheme': None, 'label': None}, {'term': u'blogging', 'scheme': None, 'label': None}, {'term': u'stuff', 'scheme': None, 'label': None}, {'term': u'Videos', 'scheme': None, 'label': None}]

我要把它交给这个:

Video Blogging, blogging, stuff, Videos

解决这个问题的最佳方法是什么?感谢您的帮助,谢谢!你知道吗


Tags: 方法字符串脚本noneapivideolabelvideos
3条回答

对于这种特殊情况,您可以使用列表:

    list_of_stuff = [
            {'term': u'Video Blogging', 'scheme': None, 'label': None}, 
            {'term': u'blogging', 'scheme': None, 'label': None}, 
            {'term': u'stuff', 'scheme': None, 'label': None}, 
            {'term': u'Videos', 'scheme': None, 'label': None}
            ]     

    parsed_string = ', '.join([d['term'] for d in list_of_stuff])
>>> l = [{'term': u'Video Blogging', 'scheme': None, 'label': None}, {'term': u'blogging', 'scheme': None, 'label': None}, {'term': u'stuff', 'scheme': None, 'label': None}, {'term': u'Videos', 'scheme': None, 'label': None}]
>>> [a.get('term') for a in l]
[u'Video Blogging', u'blogging', u'stuff', u'Videos']

如果要以逗号分隔的字符串形式获取项目,请使用:

>>> ', '.join(a.get('term') for a in l)
u'Video Blogging, blogging, stuff, Videos'

我使用a.get('term')而不是a['term']来避免没有term键的项使用KeyError。你知道吗

应该是这样的:

>>> l = [{'term': u'Video Blogging', 'scheme': None, 'label': None}, {'term': u'blogging', 'scheme': None, 'label': None}, {'term': u'stuff', 'scheme': None, 'label': None}, {'term': u'Videos', 'scheme': None, 'label': None}]
>>> ', '.join([d['term'] for d in l])
u'Video Blogging, blogging, stuff, Videos'

相关问题 更多 >