Skip to content

Instantly share code, notes, and snippets.

@edne
Created June 18, 2015 19:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edne/64bd0041559f0792f869 to your computer and use it in GitHub Desktop.
Save edne/64bd0041559f0792f869 to your computer and use it in GitHub Desktop.
utilizzo real-world di python
# Politecnico Open unix Labs (https://poul.org)
# Edoardo Negri (http://edne.net)
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
from tweepy import Stream
import json
# per poter usare le API di Twitter è necessario registare l'app
# https://apps.twitter.com/
access_token = "XXXXXXX"
access_token_secret = "XXXXXXX"
consumer_key = "XXXXXXX"
consumer_secret = "XXXXXXX"
# autenticazione
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
class Listener(StreamListener):
"""Listener che salva sul file tweets.json"""
def on_data(self, json_data):
"""funzione chiamata all'arrivo di un tweet"""
with open("tweets.json", "a") as f:
f.write(json_data)
# print(json_data)
def on_error(self, status):
"""funzione chiamata in caso di errore"""
print(status)
listener = Listener()
stream = Stream(auth, listener)
# decommentare per far partire lo stream
# stream.filter(track=["python"])
# ctrl-C per uccidere il processo
# Apro il file con i tweet salvati
with open("tweets.json") as f:
tweets_json = f.readlines() # lista di stringhe
def load(s):
"""funione per convertire una stringa (json) in un dizionario"""
try:
return json.loads(s)
except ValueError:
# se la conversione non riesce ritorna None
return None
# applico load all'intera lista
tweets_data = [load(tw_j) for tw_j in tweets_json]
# rimuovo gli elementi che sono None
# (l'operatore if si aspetta una variabile di tipo logico, i valori 0, [] e
# None vengono convertiti a False, tutto il resto a True)
tweets_data = [tw for tw in tweets_data if tw]
#
# Disegno il grafico a torta lingue e numero tweet
#
from collections import Counter
from matplotlib import pyplot as plt # http://matplotlib.org/
# lista linguaggi (ripetuti)
langs = [tw["lang"] for tw in tweets_data]
# dizionario {lingua: n_occorrenze}
counted = Counter(langs)
# dizionario con solo le lingue con più di 100 tweet
top = {k: v for (k, v) in counted.items() if v > 100}
# lista con i numeri dei tweet nelle antre lingue
others = [v for (k, v) in counted.items() if v <= 100]
# aggiungo il campo "others" al dizionario
others_sum = sum(others)
top["others"] = others_sum
sizes = list(top.values())
labels = list(top.keys())
# http://matplotlib.org/examples/pie_and_polar_charts/pie_demo_features.html
plt.pie(sizes, labels=labels)
plt.show(block=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment