【问题标题】:How to extract only texts in hashtag using tweepy?如何使用 tweepy 仅提取主题标签中的文本?
【发布时间】:2017-11-25 18:58:20
【问题描述】:

我想为我的情绪分析项目提取主题标签,但是我得到了一个字典列表,其中包含所有主题标签及其在推文中的索引。我只想要文字。

我的代码:

data = tweepy.Cursor(api.search, q, since=a[i], until=b[i]).items()
    tweet_data = []
    tweets = pd.DataFrame()
    tweets['Tweet_ID'] = map(lambda tweet: tweet['id'], tweet_data)
    tweets['Tweet'] = map(lambda tweet: tweet['text'].encode('utf-8'), tweet_data)
    tweets['Date'] = map(lambda tweet: time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(tweet['created_at'],'%a %b %d %H:%M:%S +0000 %Y')), tweet_data)
    tweets['User'] = map(lambda tweet: tweet['user']['screen_name'], tweet_data)
    tweets['Follower_count'] = map(lambda tweet: tweet['user']['followers_count'], tweet_data)
    tweets['Hashtags']=map(lambda tweet: tweet['entities']['hashtags'], tweet_data)

电流输出:

df=pd.DataFrame({'Hashtags' : [{u'indices': [53, 65], u'text': u'Predictions'}, {u'indices': [67, 76], u'text': u'FreeTips'}, {u'indices': [78, 89], u'text': u'SoccerTips'}, {u'indices': [90, 103], u'text': u'FootballTips'}, {u'indices': [104, 110], u'text': u'Goals'}]})

预期输出:

df=pd.DataFrame({'Hashtags' :["u'Predictions'", "u'SoccerTips'", "u'FootballTips'", "u'Goals'"]})

我尝试使用几种方法来展平/减少/访问包含字典列表的嵌套字典。请帮忙。

错误:

正如@MSeifert 所建议的,我已经尝试过他的方法。产生了以下错误:

dt=tweet.entities.hashtags
pd.io.json.json_normalize(dt, 'hashtags')
pd.io.json.json_normalize(dt, 'hashtags')['text'].tolist()

Traceback (most recent call last): <\br>

File "<ipython-input-166-be11241611d6>", line 1, in <module>
dt=tweet.entities.hashtags

AttributeError: 'dict' object has no attribute 'entities'

我也试过这样做:-

dx = tweets['Hashtags']
for key, value in dx.items():
    print key, value

出现以下错误:-

Traceback (most recent call last):

File "<ipython-input-167-d66c278ec072>", line 2, in <module>
    for key, value in dx.items():

File "C:\ANACONDA\lib\site-packages\pandas\core\generic.py", line 2740, in __getattr__
    return object.__getattribute__(self, name)

AttributeError: 'Series' object has no attribute 'items'

更新:

我可以访问嵌套主题标签字典的文本部分

tweets['Hashtags'][1][1]['text']
Out[209]: u'INDvPAK'

我想创建一个循环来附加行中的所有主题标签。

【问题讨论】:

    标签: python list pandas dictionary tweepy


    【解决方案1】:

    这是解决方案:

    在排查和尝试了很多方法之后,我终于弄清楚了如何拆分嵌套字典。 这是一个相当简单的循环。我注意到我们可以通过

    访问主题标签文本
    tweets['Hashtags'][1][1]['text']
    Out[209]: u'INDvPAK'
    

    这是一个宝贵的见解,因为我知道我不需要提及 u'text 作为我的索引。将使用text

    代码:

    ht=[]
    for s in range(len(tweets['Hashtags'])):
        hasht=[]
        for t in range(len(tweets.Hashtags[s])):
            #zx = tweets['Hashtags'][s][t]['text']
            hasht.append(tweets['Hashtags'][s][t]['text'])
            t=t+1
        ht.append(hasht)
        s=s+1
    tweets['HT']=zip(ht)
    

    这是一个简单的嵌套 for 循环,它首先遍历 { "Indices" : [], "u'text'" : []} 中的内部键值,然后遍历 ["entities" : { "Hashtags" : [{1},{2},{3}]}] 下的字典列表

    最后我使用zip() 压缩单个行/用户的主题标签列表。

    输出:

    ([u'SoccerTips', u'FootballTips'],)
    

    这很容易拆分。

    【讨论】:

      【解决方案2】:

      您可以使用json_normalize 函数来代替DataFrame 构造函数:

      >>> import pandas as pd
      >>> d = {'Hashtags' : 
      ...      [{u'indices': [53, 65], u'text': u'Predictions'}, 
      ...       {u'indices': [67, 76], u'text': u'FreeTips'}, 
      ...       {u'indices': [78, 89], u'text': u'SoccerTips'}, 
      ...       {u'indices': [90, 103], u'text': u'FootballTips'}, 
      ...       {u'indices': [104, 110], u'text': u'Goals'}]}
      >>>  pd.io.json.json_normalize(d, 'Hashtags')
            indices          text
      0    [53, 65]   Predictions
      1    [67, 76]      FreeTips
      2    [78, 89]    SoccerTips
      3   [90, 103]  FootballTips
      4  [104, 110]         Goals
      

      那么您可以只使用'text' 列:

      >>> pd.io.json.json_normalize(d, 'Hashtags')['text'].tolist()
      [u'Predictions', u'FreeTips', u'SoccerTips', u'FootballTips', u'Goals']
      

      【讨论】:

      • 嗨@MSeifert,它给了我以下错误,自过去几个小时以来我一直在尝试解决。请原谅我,因为我对 python 和编程很陌生。 dt=tweet.entities.hashtags ---pd.io.json.json_normalize(dt, 'hashtags') ---pd.io.json.json_normalize(dt, 'hashtags')['text'].tolist() ---Traceback (most recent call last): &lt;\br&gt; File "&lt;ipython-input-166-be11241611d6&gt;", line 1, in &lt;module&gt; dt=tweet.entities.hashtags AttributeError: 'dict' object has no attribute 'entities'
      • 你能在你的问题中添加那个(用正确的缩进)吗?在没有缩进的情况下很难在 cmets 中检查这些代码 sn-ps。 :)
      猜你喜欢
      • 2023-01-19
      • 2021-07-09
      • 2017-12-10
      • 1970-01-01
      • 2014-01-20
      • 2017-09-20
      • 2018-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多