The Python packages we import at the start are vital as they are dependencies for the python-twitter and watson-developer-cloudpackages we manually installed earlier. Without them, the python-twitter and watson-developer-cloudpackages won't function correctly.
When the analyse() function is called, it accesses the Twitter api via our app using the keys provided to gather the tweets we need from the Twitter handle we've selected - it gathers 200 tweets and excludes retweets so it's only interested in gathering what the user has tweeted. We then create an empty string to store the data we receive from Twitter and use an if statement to only include tweets that are in English and then encode them in UTF-8, which PI understands instead of Unicode, which Twitter understands.
The tweets are then pushed to PI - accessed via our credentials - who analyses the tweets and returns the data. By default, PI creates a tree structure for various categories. These categories are broken into Personality, Values, and Needs. These are then are broken into subcategories, and finally, broken into the the actual traits. We use the flatten() function to flatten the JSON structure that the analyse() function returns from PI.
We use the sorted() function to sort the results returned to us by PI. The results are sorted highest to lowest and show the 5 highest values according to PI based on the tweets. Finally, we then print the username of the account and the results to the console, and make sure to limit it to just 5 that we want to see.
Once you're finished coding and you're ready to run, open up your terminal again and type: