開始使用免費開始

載入並探索你的 Twitter 資料

現在你已把 Twitter 資料存成本機的文字檔,是時候來探索它了!接下來幾個互動式練習會帶你完成這件事。在這個練習中,你會把 Twitter 資料讀入一個清單:tweets_data

請注意,這是來自 Twitter 的真實資料,因此可能含有粗俗或其他冒犯性的內容(本練習以及之後任何同樣使用真實 Twitter 資料的練習皆然)。

本練習屬於課程

Python 資料匯入進階

檢視課程

練習說明

  • 將檔名 'tweets.txt' 指派給變數 tweets_data_path
  • tweets_data 初始化為空清單,用來儲存推文。
  • for line in tweets_file: 啟動的 for 迴圈中,使用 json.loads() 將每則推文載入變數 tweet,接著用 append() 方法把 tweet 加入 tweets_data
  • 按下送出並在終端機中檢查看到的第一筆推文字典的鍵。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Import package
import json

# String of path to file: tweets_data_path


# Initialize empty list to store tweets: tweets_data


# Open connection to file
tweets_file = open(tweets_data_path, "r")

# Read in tweets and store in list: tweets_data
for line in tweets_file:
    ____
    ____

# Close connection to file
tweets_file.close()

# Print the keys of the first tweet dict
print(tweets_data[0].keys())
編輯並執行程式碼