gpt4 book ai didi

python - 一组推文中所有主题标签的计数

转载 作者:太空宇宙 更新时间:2023-11-04 10:34:44 25 4
gpt4 key购买 nike

我有一些来自流式 API 的 JSON Twitter 数据,我想使用 Counter 函数来了解该数据集中最流行的主题标签。我遇到的问题是遍历具有多个主题标签的推文,而不是只提取第一个主题标签并忽略任何剩余的主题标签。

问题:如何遍历字典中的嵌套列表以提取推文中的所有主题标签,而不仅仅是第一个主题标签?

In [1]: import json

In [2]: from collections import Counter

In [3]: data = []

In [4]: for line in open('DC.json'):
...: try:
...: data.append(json.loads(line))
...: except:
...: pass
...:

In [5]: hashtags = []

In [6]: for i in data:
...: if 'entities' in i and len(i['entities']['hashtags']) > 0:
...: hashtags.append(i['entities']['hashtags']['text'])
...: else:
...: pass
...:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-66d7538509f9> in <module>()
1 for i in data:
2 if 'entities' in i and len(i['entities']['hashtags']) > 0:
----> 3 hashtags.append(i['entities']['hashtags']['text'])
4 else:
5 pass

TypeError: list indices must be integers, not str

In [7]: Counter(hashtags).most_common()[:10]

i['entities']['hashtags'] 中包含 4 个主题标签的示例

In [12]: i[0]['entities']['hashtags']
Out[12]:
[{u'indices': [28, 35], u'text': u'selfie'},
{u'indices': [82, 92], u'text': u'omg'},
{u'indices': [93, 104], u'text': u'Champ'},
{u'indices': [105, 117], u'text': u'FIRST'}]

最佳答案

你说 i['entities']['hashtags']dictlist,所以行:

hashtags.append(i['entities']['hashtags']['text'])

正在尝试使用字符串索引列表。这使没有意义,并导致错误。我认为您最好将其分成几步,首先获取所有 'hashtag' 词典:

hashtags = []
for i in data:
if 'entities' in i:
hashtags.extend(i['entities']['hashtags'])

然后提取'text':

hashtags = [tag['text'] for tag in hashtags]

然后将其转储到Counter:

Counter(hashtags).most_common()[:10]

关于python - 一组推文中所有主题标签的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24143905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com