Python function to find the country of origin of a Tweet

This is a rudimentary function to trace the origin from the tweet’s JSON structure. I am using a dictionary of states and abbreviations.

  def checklocation(self,data):
       location = data.get('user').get('location')
       place = data.get('place')
       if place:
           country = data.get('place').get('country')
           full_name = data.get('place').get('full_name')
           for c in self.states.itervalues():
                   p = re.compile(c.lower(), re.IGNORECASE)
                   if country:
                       m = p.match(country.lower())
                       if m:
                           return m.group()
                   if full_name:
                       m = p.match(full_name.lower())
                       if m:
                           return m.group()
                   if location:
                       m = p.match(location.lower())
                       if m:
                           return m.group()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: