CSCI 2133 RAPID PROGRAMMING TECHNIQUES FOR INNOVATION Lab
CSCI 2133 RAPID PROGRAMMING TECHNIQUES FOR INNOVATION Lab 05: Prep Lab: Python Regex and Tweepy scripting Instructor: Gang Liu Faculty of Computer Science Dalhousie University
Lab Overview ■ Introduction to regex in python ■ re. match() ■ re. search() ■ re. sub() ■ re. findall() ■ re. finditer() ■ RE Flags ■ Examples ■ Tweepy Scripting
Introduction to regex in python ■ A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used in UNIX world. [1] ■ In python, it is imported as a packaged called as “re”. >import re
Some common expressions [2]
Python re. match()
Python re. search()
Difference between match() and search()
Python re. sub()
Python re. findall()
Python re. finditer()
Python re flags
Python re. compile() ■ Python takes a lot of effort to compile your regex patterns. So if you are going to be repeatedly using a pattern, compile first and then use. Ø Import re Ø S = “Hi” Ø Pattern = re. compile(r’Hi’) Ø Pattern. match(S) PATTERN IS DISPLAYED - HI
Set up API keys for twitter script ■ #Twitter Profiler app. This is a simple script to configure the Twitter API ■ import tweepy ■ import time # Twitter API credentials. Get yours from apps. twitter. com. Twitter acct rquired # If you need help, visit https: //dev. twitter. com/oauth/overview ■ CONSUMER_KEY = "" ■ CONSUMER_SECRET = "" ■ ACCESS_KEY = "" ■ ACCESS_SECRET = ""
Get profile function (Github, 2019) ■ # this function collects a twitter profile request and returns a Twitter object def get_profile(screen_name): auth = tweepy. OAuth. Handler(CONSUMER_KEY, CONSUMER_SECRET) auth. set_access_token(ACCESS_KEY, ACCESS_SECRET) api = tweepy. API(auth) try: user_profile = api. get_user(screen_name) except: user_profile = "broken” return user_profile
Print the profile ■ s = get_profile("itisprashanth") ■ print("Name: " + s. name) ■ print("Location: " + s. location) ■ print("Description: " + s. description)
Cheatsheets – Regex and tweepy ■ https: //www. debuggex. com/cheatsheet/regex/python ■ http: //docs. tweepy. org/en/v 3. 5. 0/api. html ■ https: //www. tutorialspoint. com/python_reg_expressions. htm
References ■ Git. Hub. (2019). cdconrad/shiftkey-py. [online] Available at: https: //github. com/cdconrad/shiftkey-py [Accessed 4 Feb. 2019]. ■ Some material in the lab tutorials are and will be borrowed from Dr. Vlado Keselj, the previous instructor of this course.
- Slides: 17