วิเคราะห์ข้อความจาก Twitter เบื้องต้น
เมื่อเตรียม DataFrame ของทวีตพร้อมแล้ว เราจะมาวิเคราะห์ข้อความเพื่อนับว่ามีทวีตกี่รายการที่มีคำว่า 'clinton', 'trump', 'sanders' และ 'cruz' ใน pre-exercise code มีการกำหนดฟังก์ชัน 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 ระดับกลาง
คำแนะนำการฝึกหัด
- ภายใน
forloopfor index, row in df.iterrows():โค้ดปัจจุบันจะเพิ่มค่าของclintonขึ้น1ทุกครั้งที่พบทวีต (แถวข้อความ) ที่กล่าวถึง 'Clinton' ให้เติมโค้ดให้ครบเพื่อให้เกิดผลเช่นเดียวกันกับtrump,sandersและcruz
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# 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(____, ____)