我已經開始使用 snscrape 為我的專案獲取 Twitter 資料。我以串列格式輸出資料并使用 pandas 正確可視化它。因為參與資料不是恒定的并且會不斷更新。我正在嘗試使用 for 回圈和 if 陳述句來比較和更新它(如果需要),但是當我嘗試使用 index 訪問串列中的特定屬性時,例如:
喜歡,轉發和回復計數
它給了我一個索引錯誤。
腳本
#get data
import snscrape.modules.twitter as sntwitter
import pandas as pd
tweets_list1 = []
for i, tweet in enumerate(sntwitter.TwitterSearchScraper('from:TheHoopCentral').get_items()):
if i > 100:
break
tweets_list1.append([tweet.content, tweet.id,tweet.likeCount, tweet.retweetCount, tweet.replyCount, tweet.user.username])
print(tweets_list1)
tweets_df1 = pd.DataFrame(tweets_list1, columns=['text', 'Tweet id','LikeCount', 'RetweetCount', 'ReplyCount', 'Username'])
tweets_df1.head()
#updating engagement
tweets_list1 = []
for i, tweet in enumerate(sntwitter.TwitterSearchScraper('TheHoopCentral').get_items()):
if tweet.likeCount > tweets_list1[2]:
tweets_list1.insert(2, tweet.likeCount)
elif i > 100:
break
錯誤
IndexError Traceback (most recent call last)
<ipython-input-26-c679f6d5eecc> in <module>
3 tweets_list1 = []
4 for i, tweet in enumerate(sntwitter.TwitterSearchScraper('TheHoopCentral').get_items()):
----> 5 if tweet.likeCount > tweets_list1[2]:
6 tweets_list1.insert(2, tweet.likeCount)
7 elif i > 100:
IndexError: list index out of range
uj5u.com熱心網友回復:
在我看來,主要問題是在更新參與部分中重新分配了 tweets_list1。
在執行回圈邏輯之前,您似乎正在為變數tweets_list1分配一個空串列
tweets_list1 = [] # <-- Here
for i, tweet in enumerate(sntwitter.TwitterSearchScraper('TheHoopCentral').get_items()):
if tweet.likeCount > tweets_list1[2]:
tweets_list1.insert(2, tweet.likeCount)
elif i > 100:
break
然后,在第一個回圈期間,您將嘗試訪問空串列的第三個元素,從而導致錯誤。
tweets_list1 = []
for i, tweet in enumerate(sntwitter.TwitterSearchScraper('TheHoopCentral').get_items()):
if tweet.likeCount > tweets_list1[2]: # <-- Here
tweets_list1.insert(2, tweet.likeCount)
elif i > 100:
break
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/425638.html
上一篇:遍歷python中的兩個串列
下一篇:根據條件洗掉串列的重復項
