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

如何用Python在Pandas中生成带对话ID的推文超链接新列

解决方案

方法一:爬取循环中直接构造URL(推荐,效率更高)

修改列名列表新增tweet_url列,同时在循环里直接构造推文URL并加入数据:

columns = ['conservation id',
           'created_at', 
           'likes', 
           'full_text', 
           'retweet count', 
           'user location', 
           'user name', 
           'user verified', 
           'in reply to status?', 
           'language',
           'tweet_url']  # 新增推文URL列
data = []

for tweet in tweets:
    # 用推文作者用户名和对话ID构造完整URL
    tweet_url = f"https://twitter.com/{tweet.user.screen_name}/status/{tweet.id_str}"
    data.append([tweet.id_str, 
                 tweet.created_at, 
                 tweet.favorite_count, 
                 tweet.full_text, 
                 tweet.retweet_count, 
                 tweet.user.location, 
                 tweet.user.screen_name, 
                 tweet.user.verified, 
                 tweet.in_reply_to_status_id, 
                 tweet.lang,
                 tweet_url])  # 将URL加入数据列表

df = pd.DataFrame(data, columns=columns)

print(df)
df.to_csv('testrun.csv')

方法二:生成DataFrame后添加URL列

如果不想修改爬取循环代码,可利用已有的user name和conservation id列构造URL:

# 保留你原有的列名与循环代码
columns = ['conservation id',
           'created_at', 
           'likes', 
           'full_text', 
           'retweet count', 
           'user location', 
           'user name', 
           'user verified', 
           'in reply to status?', 
           'language']
data = []

for tweet in tweets:
    data.append([tweet.id_str, 
                 tweet.created_at, 
                 tweet.favorite_count, 
                 tweet.full_text, 
                 tweet.retweet_count, 
                 tweet.user.location, 
                 tweet.user.screen_name, 
                 tweet.user.verified, 
                 tweet.in_reply_to_status_id, 
                 tweet.lang])

df = pd.DataFrame(data, columns=columns)

# 新增推文URL列
df['tweet_url'] = df.apply(lambda row: f"https://twitter.com/{row['user name']}/status/{row['conservation id']}", axis=1)

print(df)
df.to_csv('testrun.csv')

两种方法都能生成你需要的twitter.com/user/status/(conversation_id)格式推文URL,保存CSV时会自动包含该列。

内容的提问来源于stack exchange,提问作者Mohammad Amaan Siddiqui

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 03:55:17