Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

import snscrape.modules.twitter as sntwitter query = "Seattle Kraken" for tweet in…

  1. User

    import snscrape.modules.twitter as sntwitter

    query = "Seattle Kraken" for tweet in sntwitter.TwitterSearchScraper(query).get_items(): print(vars(tweet))

    could you please tell me how to make it only print the last 100 item and also save them to a csv file please and thank you

  2. Assistant

    Sure, here's the modified code to print and save the last 100 tweets to a CSV file:

    import snscrape.modules.twitter as sntwitter
    import csv
    
    # Define the query.
    query = "Seattle Kraken"
    
    # Create a list to append the tweets to.
    tweets_list = []
    
    # Using TwitterSearchScraper to scrape tweets based on the query.
    for i, tweet in enumerate(sntwitter.TwitterSearchScraper(query).get_items()):
        # Stop when 100 tweets are retrieved.
        if i > 99:
            break
        # Get the properties of the tweet and append it to the list.
        tweets_list.append([tweet.date, tweet.id, tweet.content, tweet.user.username])
    
    # Write the tweets to a CSV file.
    with open('tweets.csv', 'w', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerow(["date", "id", "content", "username"])
        writer.writerows(tweets_list)
        print("CSV file successfully saved")
    
    # Print the tweets.
    for tweet in tweets_list:
        print(tweet)
    

    This code stops the loop when 100 tweets are retrieved, and saves the properties of each tweet to a list called tweets_list. The tweets are written to a CSV file named tweets.csv using the csv module. The first row of the CSV file contains the headers "date", "id", "content", and "username". The updated code also prints the tweets to the console.

    Let me know if you have any questions!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.