Анализ настроений в Твиттере на основе выбранных пользователей - PullRequest
1 голос
/ 03 октября 2019

Мне нужен совет по анализу настроений в Твиттере. Я пытаюсь сделать довольно общий анализ настроений, но не на случайных твитах из поиска в Твиттере, а на твитах отобранных пользователей.

То, что я до сих пор пробовал, это то, что я читал в этом CSV пользователей. А затем перебрал этот список, а затем пользователь за пользователем провел этот анализ твитов. Я поставлю здесь свою функцию write_tweets, просто чтобы она могла получить некоторую обратную связь, может быть:)

def write_tweets(users_df, file):
    # If the file exists, then read the existing data from the CSV file.
    if os.path.exists(file):
        df = pd.read_csv(file, header=0)
    else:
        df = pd.DataFrame(columns=COLS)
    #page attribute in tweepy.cursor and iteration
    for user in users_df[0]:
    #for user in users_list:
        print(user)
        #user = 'fion_li'

        try:
        #for status in tweepy.Cursor(api.user_timeline, screen_name=user, count = 1,tweet_mode="extended").items(22):
        for status in tweepy.Cursor(api.user_timeline, screen_name=user, count = 1,tweet_mode="extended").items(1):


            #print(status)
            new_entry = []
            status = status._json
            #print(to_datetime(status['created_at']))
            #print(status['full_text'])

            #csvFile = open(file, 'a' ,encoding='utf-8')

            if (to_datetime(status['created_at']) < startDate):
                 #print(to_datetime(status['created_at']))
                 #print(status['full_text'])

                continue


            ## check whether the tweet is in english or skip to the next tweet
            if status['lang'] != 'en':
                continue



           #tweepy preprocessing called for basic preprocessing
            #clean_text = clean(status['entities'])
            clean_text = clean(status['full_text'])


            #call clean_tweet method for extra preprocessing
            filtered_tweet=clean_tweets(clean_text)

            #pass textBlob method for sentiment calculations
            blob = TextBlob(filtered_tweet)
            blob_2 = TextBlob(filtered_tweet, analyzer=NaiveBayesAnalyzer())

            Sentiment = blob.sentiment
            Sentiment_2 = blob_2.sentiment

            #seperate polarity and subjectivity in to two variables
            polarity = Sentiment.polarity
            subjectivity = Sentiment.subjectivity

            positivity = Sentiment_2.p_pos
            negativity = Sentiment_2.p_neg


            #new entry append
            new_entry += [status['id'], status['created_at'],
                          status['source'],
                          #status['full_text'],
                          filtered_tweet, Sentiment,polarity,subjectivity, positivity, negativity, status['lang'],
                          status['favorite_count'], status['retweet_count']]

            #to append original author of the tweet
            new_entry.append(status['user']['screen_name'])

            try:
                is_sensitive = status['possibly_sensitive']
            except KeyError:
                is_sensitive = None
            new_entry.append(is_sensitive)

            # hashtagas and mentiones are saved using comma separted
            hashtags = ", ".join([hashtag_item['text'] for hashtag_item in status['entities']['hashtags']])
            new_entry.append(hashtags)
            mentions = ", ".join([mention['screen_name'] for mention in status['entities']['user_mentions']])
            new_entry.append(mentions)

            #get location of the tweet if possible
            try:
                location = status['user']['location']
            except TypeError:
                location = ''
            new_entry.append(location)

            try:
                coordinates = [coord for loc in status['place']['bounding_box']['coordinates'] for coord in loc]
            except TypeError:
                coordinates = None
            new_entry.append(coordinates)

            single_tweet_df = pd.DataFrame([new_entry], columns=COLS)
            #print(single_tweet_df)
            df = df.append(single_tweet_df, ignore_index=True)
            csvFile = open(file, 'a' ,encoding='utf-8')
        except Exception, e:
         pass
    #csvFile = open(file, 'a' ,encoding='utf-8')         
    df.to_csv(csvFile, mode='a', columns=COLS, index=False, encoding="utf-8")


write_tweets(users_list,  test_file)

Результатом будет несколько индикаторов настроения, таких как позитивность, негативность, нейтральность и т. Д. Мой вопрос заключается в том, чтоможет быть, некоторые из вас уже сделали подобные вещи и могут дать мне несколько советов по этому поводу? Моя версия кажется очень медленной и не очень эффективной (по крайней мере, для меня).

Заранее спасибо

...