Guest User

Untitled

a guest
Oct 5th, 2011
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.32 KB | None | 0 0
  1. """Visualizing Twitter Sentiment Across America"""
  2.  
  3. import string
  4. from data import word_sentiments, load_tweets
  5. from geo import us_states, geo_distance, make_position, longitude, latitude
  6. from maps import draw_state, draw_name, draw_dot, wait
  7. from ucb import main, trace, interact, log_current_line
  8. import doctest
  9.  
  10. # Phase 1: The feelings in tweets
  11.  
  12. def make_tweet(text, time, lat, lon):
  13.     """Return a tweet, represented as a python dictionary.    
  14.  
  15.    text -- A string; the text of the tweet, all in lowercase
  16.    time -- A datetime object; the time that the tweet was posted
  17.    lat -- A number; the latitude of the tweet's location
  18.    lon -- A number; the longitude of the tweet's location
  19.    """
  20.     return {'text': text, 'time': time, 'latitude': lat, 'longitude': lon}
  21.  
  22. def tweet_words(tweet):
  23.     """Return a list of words in the tweet.
  24.    
  25.    Arguments:
  26.    tweet -- a tweet abstract data type.
  27.    
  28.    Return 1 value:
  29.     - The list of words in the tweet.
  30.    """
  31.     text = tweet['text']
  32.     return extract_words(text)
  33.  
  34. def tweet_location(tweet):
  35.     """Return a position (see geo.py) that represents the tweet's location."""
  36.     latitude = tweet['latitude']
  37.     longitude = tweet['longitude']
  38.     return make_position(latitude, longitude)
  39.  
  40. def tweet_string(tweet):
  41.     """Return a string representing the tweet."""
  42.     return '"{0}" @ {1}'.format(tweet['text'], tweet_location(tweet))
  43.  
  44. def extract_words(text):
  45.     """Return the words in a tweet, not including punctuation.
  46.  
  47.    >>> extract_words('anything else.....not my job')
  48.    ['anything', 'else', 'not', 'my', 'job']
  49.    >>> extract_words('i love my job. #winning')
  50.    ['i', 'love', 'my', 'job', 'winning']
  51.    >>> extract_words('make justin # 1 by tweeting #vma #justinbieber :)')
  52.    ['make', 'justin', 'by', 'tweeting', 'vma', 'justinbieber']
  53.    >>> extract_words("paperclips! they're so awesome, cool, & useful!")
  54.    ['paperclips', 'they', 're', 'so', 'awesome', 'cool', 'useful']
  55.    """
  56.     for word in text:
  57.         if word == '.' or word == '\'':
  58.             b = text.replace(word, ' ')
  59.             text = b
  60.         elif word not in string.ascii_letters and word != ' ':
  61.             b = text.replace(word, '')
  62.             text = b
  63.     return text.split()
  64.  
  65. def get_word_sentiment(word):
  66.     """Return a number between -1 and +1 representing the degree of positive or
  67.    negative feeling in the given word.
  68.  
  69.    Return None if the word is not in the sentiment dictionary.
  70.    (0 represents a neutral feeling, not an unknown feeling.)
  71.    
  72.    >>> get_word_sentiment('good')
  73.    0.875
  74.    >>> get_word_sentiment('bad')
  75.    -0.625
  76.    >>> get_word_sentiment('winning')
  77.    0.5
  78.    >>> get_word_sentiment('Berkeley')  # Returns None
  79.    """
  80.     return word_sentiments.get(word, None)
  81.  
  82. def analyze_tweet_sentiment(tweet):
  83.     """ Return a number between -1 and +1 representing the degree of positive or
  84.    negative sentiment in the given tweet, averaging over all the words in the
  85.    tweet that have a sentiment score.
  86.  
  87.    If there are words that don't have a sentiment score, leave them
  88.    out of the calculation.
  89.  
  90.    If no words in the tweet have a sentiment score, return None.
  91.    (do not return 0, which represents neutral sentiment).
  92.  
  93.    >>> positive = make_tweet('i love my job. #winning', None, 0, 0)
  94.    >>> round(analyze_tweet_sentiment(positive), 5)
  95.    0.29167
  96.    >>> negative = make_tweet("Thinking, 'I hate my job'", None, 0, 0)
  97.    >>> analyze_tweet_sentiment(negative)
  98.    -0.25
  99.    >>> no_sentiment = make_tweet("Go bears!", None, 0, 0)
  100.    >>> analyze_tweet_sentiment(no_sentiment)
  101.    """
  102.     average = None
  103.     text = tweet['text']
  104.     a = extract_words(text)
  105.     total = 0
  106.     counter = 0
  107.     for word in a:
  108.         if type(get_word_sentiment(word)) == float:
  109.             total = total + get_word_sentiment(word)
  110.             counter = counter + 1
  111.     if counter == 0:
  112.         return average
  113.     average = total/counter
  114.     return average
  115.  
  116. #@main
  117. def print_sentiment(text='Are you virtuous or verminous?'):
  118.     """Print the words in text, annotated by their sentiment scores.
  119.  
  120.    For example, to print each word of a sentence with its sentiment:
  121.  
  122.    # python3 trends.py "computer science is my favorite!"
  123.    """
  124.     words = extract_words(text.lower())
  125.     assert words, 'No words extracted from "' + text + '"'
  126.     layout = '{0:>' + str(len(max(words, key=len))) + '}: {1}'
  127.     for word in extract_words(text.lower()):
  128.         print(layout.format(word, get_word_sentiment(word)))
  129.  
  130.  
  131.  
  132. # Phase 2: The geometry of maps
  133.  
  134. def find_centroid(polygon):
  135.     """Find the centroid of a polygon.
  136.  
  137.    http://en.wikipedia.org/wiki/Centroid#Centroid_of_polygon
  138.    
  139.    polygon -- A list of positions, in which the first and last are the same
  140.  
  141.    Returns: 3 numbers; centroid latitude, centroid longitude, and polygon area
  142.  
  143.    Hint: If a polygon has 0 area, return its first position as its centroid
  144.  
  145.    >>> p1, p2, p3 = make_position(1, 2), make_position(3, 4), make_position(5, 0)
  146.    >>> triangle = [p1, p2, p3, p1]  # First vertex is also the last vertex
  147.    >>> find_centroid(triangle)
  148.    (3.0, 2.0, 6.0)
  149.    >>> find_centroid([p1, p3, p2, p1])
  150.    (3.0, 2.0, 6.0)
  151.    >>> find_centroid([p1, p2, p1])
  152.    (1, 2, 0)
  153.    """
  154.     counter = 0
  155.     vertices = len(polygon) - 1
  156.     area, xcor, ycor = 0, 0, 0
  157.     while counter < vertices:
  158.         area = area + latitude(polygon[counter])*longitude(polygon[counter+1]) - latitude(polygon[counter+1])*longitude(polygon[counter])
  159.         xcor = xcor + (latitude(polygon[counter]) + latitude(polygon[counter+1]))*(latitude(polygon[counter])*longitude(polygon[counter+1]) - latitude(polygon[counter+1])*longitude(polygon[counter]))
  160.         ycor = ycor + (longitude(polygon[counter])+longitude(polygon[counter+1]))*(latitude(polygon[counter])*longitude(polygon[counter+1]) - latitude(polygon[counter+1])*longitude(polygon[counter]))
  161.         counter = counter + 1
  162.     if area < 0:
  163.         area = -area
  164.     if area == 0:
  165.         xcor = latitude(polygon[0])
  166.         ycor = longitude(polygon[0])
  167.         return xcor, ycor, area
  168.     area = area*0.5
  169.     xcor = xcor/(area*6)
  170.     ycor = ycor/(area*6)
  171.     if xcor < 0 and ycor < 0:
  172.         xcor = -xcor
  173.         ycor = -ycor
  174.    
  175.     return xcor, ycor, area
  176.  
  177. def find_center(shapes):
  178.     """Compute the geographic center of a state, averaged over its shapes.
  179.  
  180.    The center is the average position of centroids of the polygons in shapes,
  181.    weighted by the area of those polygons.
  182.    
  183.    Arguments:
  184.    shapes -- a list of polygons
  185.  
  186.    >>> ca = find_center(us_states['CA'])  # California
  187.    >>> round(latitude(ca), 5)
  188.    37.25389
  189.    >>> round(longitude(ca), 5)
  190.    -119.61439
  191.  
  192.    >>> hi = find_center(us_states['HI'])  # Hawaii
  193.    >>> round(latitude(hi), 5)
  194.    20.1489
  195.    >>> round(longitude(hi), 5)
  196.    -156.21763
  197.    """
  198.     xtotal, ytotal, atotal = 0, 0, 0
  199.     for shape in shapes:
  200.         x, y, a = find_centroid(shape)
  201.         xtotal = xtotal + x*a
  202.         ytotal = ytotal + y*a
  203.         atotal = atotal + a
  204.     latitude = xtotal/atotal
  205.     longitude = ytotal/atotal
  206.     return make_position(latitude, longitude)
  207.  
  208.  
  209. # Uncomment this decorator during Phase 2.
  210. #@main
  211. def draw_centered_map(center_state='TX', n=10):
  212.     """Draw the n states closest to center_state.
  213.    
  214.    For example, to draw the 20 states closest to California (including California):
  215.  
  216.    # python3 trends.py CA 20
  217.    """
  218.     us_centers = {n: find_center(s) for n, s in us_states.items()}
  219.     center = us_centers[center_state.upper()]
  220.     dist_from_center = lambda name: geo_distance(center, us_centers[name])
  221.     for name in sorted(us_states.keys(), key=dist_from_center)[:int(n)]:
  222.         draw_state(us_states[name])
  223.         draw_name(name, us_centers[name])
  224.     draw_dot(center, 1, 10)  # Mark the center state with a red dot
  225.     wait()
  226.  
  227.  
  228. # Phase 3: The mood of the nation
  229.  
  230. def find_closest_state(tweet, state_centers):
  231.     """Return the name of the state closest to the given tweet's location.
  232.    
  233.    Use the geo_distance function (already provided) to calculate distance
  234.    in miles between two latitude-longitude positions.
  235.  
  236.    Arguments:
  237.    tweet -- a tweet abstract data type
  238.    state_centers -- a dictionary from state names to state shapes
  239.  
  240.    >>> us_centers = {n: find_center(s) for n, s in us_states.items()}
  241.    >>> sf = make_tweet("Welcome to San Francisco", None, 38, -122)
  242.    >>> ny = make_tweet("Welcome to New York", None, 41, -74)
  243.    >>> find_closest_state(sf, us_centers)
  244.    'CA'
  245.    >>> find_closest_state(ny, us_centers)
  246.    'NJ'
  247.    """
  248.     pos1 = tweet_location(tweet)
  249.     close = 99999999999
  250.     for n, s in state_centers.items():
  251.         x = geo_distance(pos1, s)
  252.         if x < close:
  253.             close = x
  254.             state = n
  255.        
  256.     return state
  257.  
  258. def group_tweets_by_state(tweets):
  259.     """Return a dictionary that aggregates tweets by their nearest state center.
  260.  
  261.    The keys of the returned dictionary are state names, and the values are
  262.    lists of tweets that appear closer to that state center than any other.
  263.    
  264.    tweets -- a sequence of tweet abstract data types    
  265.  
  266.    >>> sf = make_tweet("Welcome to San Francisco", None, 38, -122)
  267.    >>> ny = make_tweet("Welcome to New York", None, 41, -74)
  268.    >>> ca_tweets = group_tweets_by_state([sf, ny])['CA']
  269.    >>> tweet_string(ca_tweets[0])
  270.    '"Welcome to San Francisco" @ (38, -122)'
  271.    """
  272.     tweets_by_state = {}
  273.    
  274.     for tweet in tweets:
  275.         us_centers = {n: find_center(s) for n, s in us_states.items()}
  276.         state = find_closest_state(tweet, us_centers)
  277.         if state in tweets_by_state:
  278.             a = tweets_by_state[state]
  279.             a.append(tweet)
  280.             tweets_by_state[state] = a
  281.         else:
  282.             a = [tweet,]
  283.             tweets_by_state[state] = a
  284.            
  285.     return tweets_by_state
  286.  
  287. def calculate_average_sentiments(tweets_by_state):
  288.     """Calculate the average sentiment of the states by averaging over all
  289.    the tweets from each state. Return the result as a dictionary from state
  290.    names to average sentiment values.
  291.  
  292.    If a state has no tweets with sentiment values, leave it out of the
  293.    dictionary entirely.  Do not include a states with no tweets, or with tweets
  294.    that have no sentiment, as 0.  0 represents neutral sentiment, not unknown
  295.    sentiment.
  296.  
  297.    tweets_by_state -- A dictionary from state names to lists of tweets
  298.    """
  299.     averaged_state_sentiments = {}
  300.    
  301.     for n, s in tweets_by_state.items():
  302.         total = 0
  303.         counter = 0
  304.         for k in s:
  305.             if type(analyze_tweet_sentiment(k)) == float:
  306.                 total = total + analyze_tweet_sentiment(k)
  307.                 counter = counter + 1
  308.             if analyze_tweet_sentiment(k) == 0:
  309.                 counter = counter + 1
  310.         if counter != 0:    
  311.             average = total/counter  
  312.             averaged_state_sentiments[n] = average
  313.            
  314.     return averaged_state_sentiments
  315.  
  316.  
  317. def draw_state_sentiments(state_sentiments={}):
  318.     """Draw all U.S. states in colors corresponding to their sentiment value.
  319.    
  320.    Unknown state names are ignored; states without values are colored grey.
  321.    
  322.    state_sentiments -- A dictionary from state strings to sentiment values
  323.    """
  324.     for name, shapes in us_states.items():
  325.         sentiment = state_sentiments.get(name, None)
  326.         draw_state(shapes, sentiment)
  327.     for name, shapes in us_states.items():
  328.         center = find_center(shapes)
  329.         if center is not None:
  330.             draw_name(name, center)
  331.  
  332. # Uncomment this decorator during Phase 3.
  333. @main
  334. def draw_map_for_term(term='texas'):
  335.     """
  336.    Draw the sentiment map corresponding to the tweets that match term.
  337.    
  338.    term -- a word or phrase to filter the tweets by.  
  339.    
  340.    To visualize tweets containing the word "obama":
  341.    
  342.    # python3 trends.py obama
  343.    
  344.    Some term suggestions:
  345.    New York, Texas, sandwich, my life, justinbieber
  346.    """
  347.     tweets = load_tweets(make_tweet, term)
  348.     tweets_by_state = group_tweets_by_state(tweets)
  349.     state_sentiments = calculate_average_sentiments(tweets_by_state)
  350.     draw_state_sentiments(state_sentiments)
  351.     for tweet in tweets:
  352.         draw_dot(tweet_location(tweet), analyze_tweet_sentiment(tweet))
  353.     wait()
  354.  
  355.  
  356.  
  357.  
Advertisement
Add Comment
Please, Sign In to add comment