Tweepy ошибка с экспортом содержимого массива - PullRequest
0 голосов
/ 12 марта 2020

Я хочу извлечь твиты и записать их в файл CSV, однако я не могу понять, как заставить его генерировать файл. Я использую Tweepy для извлечения твитов. Я хотел бы, чтобы CSV-файл содержал следующие ячейки: Пользователь, дата, твит, лайки, ретвиты, итоги, рейтинг, рейтинг, идентификатор твита

import tweepy
import csv

auth = tweepy.OAuthHandler("", "")
auth.set_access_token("", "")

api = tweepy.API(auth)

try:
    api.verify_credentials()
    print("Authentication OK")
except:
    print("Error during authentication")

def timeline(username):
    tweets = api.user_timeline(screen_name=username, count = '100', tweet_mode="extended")

    for status in (tweets):
        eng = round(((status.favorite_count + status.retweet_count)/status.user.followers_count)*100, 2)
        if (not status.retweeted) and ('RT @' not in status.full_text) and (eng <= 0.02):
            print (status.user.screen_name + ',' + str(status.created_at) + ',' + status.full_text + ",Likes: " + str(status.favorite_count) + ",Retweets: " + str(status.retweet_count) + ',Total: ' + str(status.favorite_count + status.retweet_count) + ',Engagement rate: ' + str(eng) + '%' + 'Rating: Low' + ',Tweet ID: ' + str(status.id))
        elif (not status.retweeted) and ('RT @' not in status.full_text) and (0.02 < eng <= 0.09):
            print (status.user.screen_name + ',' + str(status.created_at) + ',' + status.full_text + ",Likes: " + str(status.favorite_count) + ",Retweets: " + str(status.retweet_count) + ',Total: ' + str(status.favorite_count + status.retweet_count) + ',Engagement rate: ' + str(eng) + '%' + 'Rating: Good' + ',Tweet ID: ' + str(status.id))
        elif (not status.retweeted) and ('RT @' not in status.full_text) and (0.09 < eng <= 0.33):
            print (status.user.screen_name + ',' + str(status.created_at) + ',' + status.full_text + ",Likes: " + str(status.favorite_count) + ",Retweets: " + str(status.retweet_count) + ',Total: ' + str(status.favorite_count + status.retweet_count) + ',Engagement rate: ' + str(eng) + '%' + 'Rating: High' + ',Tweet ID: ' + str(status.id))
        elif (not status.retweeted) and ('RT @' not in status.full_text) and (0.33 < eng):
            print (status.user.screen_name + ',' + str(status.created_at) + ',' + status.full_text + ",Likes: " + str(status.favorite_count) + ",Retweets: " + str(status.retweet_count) + ',Total: ' + str(status.favorite_count + status.retweet_count) + ',Engagement rate: ' + str(eng) + '%' + 'Rating: Very High' + ',Tweet ID: ' + str(status.id))
tweet = timeline("twitter")

with open('tweet.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.writer(f)
    writer.writerow([tweet])

Ответы [ 2 ]

0 голосов
/ 12 марта 2020

Ваша функция get_tweets не возвращает значение, но вы пытаетесь получить значение из этой функции, что приведет к None. Также похоже, что значением твита будет список строк. Метод writerow из csv.writer должен получать список элементов, а не список списков. Я изменил ваш код для решения этих проблем. Дайте мне знать, если это работает.

def get_tweets(username):
    tweets = api.user_timeline(screen_name=username, count=100) 
    tweets_for_csv = [tweet.text for tweet in tweets]
    print(tweets_for_csv)
    return tweets_for_csv


tweet = get_tweets("fazeclan")

with open('tweet.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerow(tweet)
0 голосов
/ 12 марта 2020

Вы можете посмотреть https://docs.python.org/3/library/csv.html для получения информации о том, как сгенерировать CSV-файл в Python. Быстрый пример:

import csv

with open('some_output.csv', 'w') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(["field1", "field2", "field3"])
...