【问题标题】:Classify type of tweet based on regex in python基于python中的正则表达式对推文类型进行分类
【发布时间】:2014-08-02 06:38:27
【问题描述】:

这个问题的扩展:Classify type of tweet (tweet/retweet/mention) based on tweet text in Python

我想将我的数据集中的每条推文分类为以下之一,并将推文类型附加到数据集中的每条记录中。目前,当我运行下面显示的脚本时,我得到了 [None] 返回,所以显然我在这里遗漏了一些东西。

当前格式:

 ['CREATED_AT']['text']

所需格式:

['CREATED_AT']['text']['tweet_type']

推文分类:

(1) 转推 --> 推文文本列某处有一个“RT @anyusername”

(2) 提及 --> 推文栏有“@anyusername”但没有“RT @anyusername”

(3) Tweet --> tweet 栏中没有“RT @anyusername”,也没有任何“@anyusername”

代码:

import json
import time
import re

# load Twitter Streaming JSON data into a dict
def import_tweets(parameter1):
    data = []
    for line in open(parameter1):
      try: 
        data.append(json.loads(line))
      except:
        pass

    for i in data:
        i['CREATED_AT'] = time.strftime('%Y-%m-%d %H:%M:%S',time.strptime(i['created_at'],'%a %b %d %H:%M:%S +0000 %Y'))
    return data

# Extract timestamp and tweet text into a list
def extract_tweets(parameter2):
    tweets = []
    for i in parameter2:
        tweets.append(
        [i['CREATED_AT'],
         i['text']]        
        )
    return tweets

# Classify each tweet as retweet/mention/tweet
def tweet_type(parameter3):
    tweet_type = []
    for i in parameter3:
        match = re.match(r'RT\s@....+', i[1])   
        if match:
            tweet_type.append([i, 'retweet'])
        else:
            match = re.match(r'@....+', i[1])
            if match:
               tweet_type.append([i, 'reply'])
            else:
                match = re.match(r'....+@', i[1])
                if match:
                   tweet_type.append([i, 'mention'])
                else:
                   tweet_type.append([i, 'tweet'])                
    return tweet_type    

data = import_tweets('tweets.json')
tweets = extract_tweets(data)
tweet_type = tweet_type(tweets)

# Print sample to make sure tweet text was classified properly
print tweet_type[:5]

【问题讨论】:

    标签: python regex twitter


    【解决方案1】:

    有两个问题:

    1. tweet_type.append(i.append(['tweet'])) -- 对list.append() 的调用不返回任何内容(意味着它们隐式返回 None)。您将 None 附加到 tweet_type。这是主要问题。

    2. return tweet_type 向右缩进太多 -- 循环在第一次迭代时退出函数。

    【讨论】:

    • @Curtis 您需要将 i.append(...) 替换为您要放置到 tweet_type 的值。因为您没有文档字符串并且每个参数都是parameter1,所以很难说出您打算在那里发生什么。 :)
    • 我的最终目标是获取推文列表(['CREATED_AT']['text'],根据推文的类型,我想将推文的类型附加到每一行,所以我最终得到@987654327 @
    • 也许您可以编辑原始帖子中的代码以使其更具可读性?
    【解决方案2】:
    import json
    import time
    import re
    
    def import_tweets(parameter1):
        """
        Loads data from Twitter Streaming API for analysis.
    
        Args:
            parameter1:  input file
        Returns:
            List of nested dictionaries
        """
    
        # load JSON data into a dict    
        data = []
        for line in open(parameter1):
            try: 
                data.append(json.loads(line))
            except:
                pass
    
        # Transform Twitter tweet date/time format into standard date/time format
        for i in data:
            i['CREATED_AT'] = time.strftime('%Y-%m-%d %H:%M:%S',time.strptime(i['created_at'],'%a %b %d %H:%M:%S +0000 %Y'))
    
        # Classify each tweet as a retweet/reply/mention/tweet
        for i in data:
            match = re.match(r'RT\s@....+', i['text'])   
            if match:
                i['TYPE'] = 'retweet'
            else:
                match = re.match(r'@....+', i['text'])
                if match:
                    i['TYPE'] = 'reply'
                else:
                    match = re.match(r'....+@', i['text'])
                    if match:
                        i['TYPE'] = 'mention'
                    else:
                        i['TYPE'] = 'tweet'
    
        return data 
    

    【讨论】:

      猜你喜欢
      • 2014-06-24
      • 2012-03-26
      • 1970-01-01
      • 2015-09-27
      • 2011-08-31
      • 1970-01-01
      • 2014-08-31
      相关资源
      最近更新 更多