
บทความนี้สอน Twitter Sentiment Analysis: สมัคร Twitter OAuth API, ติดตั้ง dependencies, เขียนสคริปต์วิเคราะห์ความรู้สึก
API (Application Programming Interface) เป็นประตูเข้าถึงฟังก์ชันภายในของเซิร์ฟเวอร์ (Twitter)
ข้อกำหนดเบื้องต้น: มีบัญชี Twitter ยืนยันเบอร์โทรแล้ว
สร้าง App ใหม่ที่เว็บไซต์ Twitter Developer กรอกข้อมูล ยอมรับข้อตกลง กด Create
ที่แท็บ Keys จะได้ OAuth credentials และ tokens
ติดตั้ง Dependencies
1. tweepy module
pip install tweepy
2. textblob module
pip install textblob
TextBlob คืออะไร?
โมดูลสำหรับ Sentiment Analysis มีเมธอดคำนวณความรู้สึกในช่วง -1 ถึง 1 ผ่าน token.sentiment.polarity
ขั้นตอนการเขียนสคริปต์
- นำ credentials มาใส่ในตัวแปร
- สร้าง authentication variable
auth = tweepy.OAuthHandler(consumer_key, consumer_secret) - ตั้งค่า access token:
auth.set_access_token(access_token, access_token_secret) - สร้าง API object:
api = tweepy.API(auth) - ค้นหาทวีตสาธารณะ:
public_tweet = api.search('Tutorialspoint') - วนลูปพิมพ์ข้อความและวิเคราะห์ด้วย TextBlob
public_tweet = api.search('Tutorialspoint')
for tweet in public_tweet:
print(tweet.text)
analysis = TextBlob(tweet.text)
print(analysis)
ผลลัพธ์จะมี Polarity (บวก/ลบ) และ Subjectivity (ความคิดเห็น/ข้อเท็จจริง)
สรุป
ด้วย Sentiment Analyzer นี้ สามารถเข้าใจและดึงความรู้สึกของมนุษย์จากข้อมูลได้