開始使用免費開始

一點點 Twitter 文字分析

現在你已經建立好推文的 DataFrame,接下來要做一點文字分析,計算有多少推文包含 'clinton''trump''sanders''cruz' 這幾個字詞。在練習前置程式碼中,我們定義了函式 word_in_text(),它會告訴你第一個引數(單字)是否出現在第二個引數(推文)中。

import re

def word_in_text(word, text):
    word = word.lower()
    text = text.lower()
    match = re.search(word, text)

    if match:
        return True
    return False

你將逐列走訪 DataFrame,計算每個關鍵字各自出現於多少則推文中!每位候選人的計數物件清單已初始化為 0。

本練習屬於課程

Python 資料匯入進階

檢視課程

練習說明

  • for 迴圈 for index, row in df.iterrows(): 中,目前的程式碼會在每次遇到提及「Clinton」的推文(文字列)時,將 clinton 的值加上 1;請完成程式碼,讓 trumpsanderscruz 也能以相同方式累計。

動手互動練習

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

# Initialize list to store tweet counts
[clinton, trump, sanders, cruz] = [0, 0, 0, 0]

# Iterate through df, counting the number of tweets in which
# each candidate is mentioned
for index, row in df.iterrows():
    clinton += word_in_text('clinton', row['text'])
    trump += word_in_text(____, ____)
    sanders += word_in_text(____, ____)
    cruz += word_in_text(____, ____)
編輯並執行程式碼