You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Twitter情感分析Python代码的结果导出为CSV文件

如何将Twitter情感分析结果导出为CSV文件?

嘿,我来帮你搞定把Twitter情感分析结果导出成CSV的问题!其实很简单,咱们可以用Python自带的csv模块,或者更省心的pandas库来实现,下面给你两种方案参考:

方案一:使用Python内置csv模块

这个方案不需要额外安装库,适合不想折腾依赖的场景:

  1. 首先在你的代码里导入csv模块
  2. 获取到分析后的推文数据后,定义要导出的字段(比如推文内容、情感极性、情感标签)
  3. 打开CSV文件并写入数据

结合你的现有代码,完整示例如下:

import re
import tweepy
from tweepy import OAuthHandler
from textblob import TextBlob
import csv  # 新增导入csv模块

class TwitterClient(object):
    ''' Generic Twitter Class for sentiment analysis. '''
    def __init__(self):
        # 填入你的Twitter API密钥
        consumer_key = '你的consumer_key'
        consumer_secret = '你的consumer_secret'
        access_token = '你的access_token'
        access_token_secret = '你的access_token_secret'
        
        try:
            self.auth = OAuthHandler(consumer_key, consumer_secret)
            self.auth.set_access_token(access_token, access_token_secret)
            self.api = tweepy.API(self.auth)
        except:
            print("认证失败,请检查你的密钥")
    
    def clean_tweet(self, tweet):
        # 清洗推文内容,去除@用户、链接和特殊字符
        return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", tweet).split())
    
    def get_tweet_sentiment(self, tweet):
        # 分析推文情感
        analysis = TextBlob(self.clean_tweet(tweet))
        if analysis.sentiment.polarity > 0:
            return {'polarity': analysis.sentiment.polarity, 'sentiment': 'positive'}
        elif analysis.sentiment.polarity == 0:
            return {'polarity': analysis.sentiment.polarity, 'sentiment': 'neutral'}
        else:
            return {'polarity': analysis.sentiment.polarity, 'sentiment': 'negative'}
    
    def get_tweets(self, query, count=10):
        # 获取推文并添加情感分析结果
        tweets = []
        try:
            fetched_tweets = self.api.search_tweets(q=query, count=count)
            for tweet in fetched_tweets:
                parsed_tweet = {}
                parsed_tweet['text'] = tweet.text
                parsed_tweet.update(self.get_tweet_sentiment(tweet.text))
                tweets.append(parsed_tweet)
            return tweets
        except tweepy.TweepyException as e:
            print(f"获取推文时出错: {e}")
            return []

# 主程序:获取推文并导出为CSV
if __name__ == "__main__":
    client = TwitterClient()
    # 替换成你的搜索关键词和需要的推文数量
    tweets = client.get_tweets(query="Python", count=50)
    
    # 定义要导出的CSV字段
    csv_fields = ['text', 'polarity', 'sentiment']
    
    # 写入CSV文件
    with open('twitter_sentiment_results.csv', 'w', newline='', encoding='utf-8') as csv_file:
        writer = csv.DictWriter(csv_file, fieldnames=csv_fields)
        writer.writeheader()  # 写入表头
        for tweet in tweets:
            writer.writerow(tweet)  # 逐行写入推文数据
    
    print("分析结果已成功导出到twitter_sentiment_results.csv!")

方案二:使用pandas库(更简洁高效)

如果你不介意安装额外库,pandas能让导出代码更简洁,还能方便后续的数据筛选、统计等操作:

  1. 先安装pandas(如果没装的话):
pip install pandas
  1. 修改你的代码,用pandas快速导出:
import re
import tweepy
from tweepy import OAuthHandler
from textblob import TextBlob
import pandas as pd  # 新增导入pandas

# 这里是你的TwitterClient类,和上面的代码一致,省略重复部分...

# 主程序:获取推文并导出为CSV
if __name__ == "__main__":
    client = TwitterClient()
    tweets = client.get_tweets(query="Python", count=50)
    
    # 将推文列表转为DataFrame格式
    tweet_df = pd.DataFrame(tweets)
    
    # 导出为CSV,index=False表示不保存自动生成的索引列
    tweet_df.to_csv('twitter_sentiment_results.csv', columns=['text', 'polarity', 'sentiment'], index=False, encoding='utf-8')
    
    print("分析结果已成功导出到twitter_sentiment_results.csv!")

小提醒:

  • 确保你的get_tweets方法返回的是包含text、polarity、sentiment字段的字典列表,如果你的字段名不同,记得对应修改CSV的字段或DataFrame的列名
  • 使用encoding='utf-8'可以避免中文或特殊字符出现乱码
  • 在Windows系统下,newline=''能避免CSV文件出现多余的空行

内容的提问来源于stack exchange,提问作者Abdullah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:41:25