In [1]:
import json, datetime
def date_hook(json_dict):
    for (key, value) in json_dict.items():
        try:
            json_dict[key] = datetime.datetime.strptime(value,'%a %b %d %H:%M:%S +0000 %Y')
        except:
            pass
    return json_dict
import sys, glob, errno
datetweets = []
path = '../data/someTweets.20141013-013654.json'   
files = glob.glob(path)   
print len(files)
for name in files:
    try:
        for line in open(name): # No need to specify 'r': this is the default.
            datetweets.append(json.loads(line, object_hook=date_hook))
    except IOError as exc:
        if exc.errno != errno.EISDIR: # Do not fail if a directory is found, just ignore it.
            raise # Propag


1

In [2]:
len(datetweets)


Out[2]:
1261

In [2]:
from os import path
import matplotlib.pyplot as plt
from wordcloud import WordCloud
import os
os.path.exists('/Users/paul/Library/Fonts/Verdana.ttf')
font_path = '/Users/carlyhendrickson/Library/Fonts/SourceCodePro-Light.otf'
text = [tweet['text'] for tweet in datetweets]
text = str(text)

In [18]:
wordcloud = WordCloud(font_path).generate(text)
wordcloud
# Open a plot of the generated image.

In [20]:
plt.imshow(wordcloud)
plt.axis("off")
plt.show()

In [1]:
import csv,codecs,cStringIO

class UTF8Recoder:
    def __init__(self, f, encoding):
        self.reader = codecs.getreader(encoding)(f)
    def __iter__(self):
        return self
    def next(self):
        return self.reader.next().encode("utf-8")

class UnicodeReader:
    def __init__(self, f, dialect=csv.excel, encoding="utf-8-sig", **kwds):
        f = UTF8Recoder(f, encoding)
        self.reader = csv.reader(f, dialect=dialect, **kwds)
    def next(self):
        '''next() -> unicode
        This function reads and returns the next line as a Unicode string.
        '''
        row = self.reader.next()
        return [unicode(s, "utf-8") for s in row]
    def __iter__(self):
        return self

class UnicodeWriter:
    def __init__(self, f, dialect=csv.excel, encoding="utf-8-sig", **kwds):
        self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()
    def writerow(self, row):
        '''writerow(unicode) -> None
        This function takes a Unicode string and encodes it to the output.
        '''
        self.writer.writerow([s.encode("utf-8") for s in row])
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        data = self.encoder.encode(data)
        self.stream.write(data)
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)

In [2]:
sentiment = []
import csv
#with open('tweet_sentiment_scores.csv', 'rb') as csvfile:
#    f = csv.reader(csvfile, delimiter=',', quotechar='"')
#    for row in f:
#        sentiment.append(row)

sentimenet = []
with open('tweet_sentiment_scores.csv','rb') as fin:
    reader = UnicodeReader(fin, quoting=csv.QUOTE_ALL)
    for line in reader:
        sentiment.append(line)

In [9]:
import gensim
#print sentiment[20][2]
s = sentiment[20][2]
s = s.split(",")
tokens = list(gensim.utils.tokenize(sentiment[0][2]))
print tokens


[u'u', u'new', u'u', u'facebook', u'u', u'posted', u'u', u'photo', u'u', u'video', u'u', u'youtube', u'u', u'my', u'u', u'from', u'u', u'liked', u'u', u'out', u'u', u'youtube', u'u', u'video', u'u', u'liked', u'u', u'from', u'u', u'amp', u'u', u'my', u'u', u'with', u'u', u'photo', u'u', u'posted', u'u', u'u', u'my', u'u', u'with', u'u', u'youtube', u'u', u'that', u'u', u'your', u'u', u'are', u'u', u'we', u'u', u'apple', u'u', u'video', u'u', u'amp', u'u', u'from', u'u', u'my', u'u', u'buy', u'u', u'song', u'u', u'last', u'u', u'with', u'u', u'please', u'u', u'us', u'u', u'help', u'u', u'most', u'u', u'my', u'u', u'with', u'u', u'amp', u'u', u'apple', u'u', u'out', u'u', u'your', u'u', u'that', u'u', u'we', u'u', u'check', u'u', u'me', u'u', u'apple', u'u', u'with', u'u', u'we', u'u', u'that', u'u', u'my', u'u', u'read', u'u', u'full', u'u', u'price', u'u', u'ebay', u'u', u'are', u'u', u'your', u'u', u'with', u'u', u'apple', u'u', u'amp', u'u', u'are', u'u', u'my', u'u', u'we', u'u', u'be', u'u', u'will', u'u', u'that', u'u', u'amp', u'u', u'with', u'u', u'apple', u'u', u'that', u'u', u'out', u'u', u'my', u'u', u'from', u'u', u'your', u'u', u'check', u'u', u'get', u'u', u'new', u'u', u'out', u'u', u'facebook', u'u', u'check', u'u', u'amp', u'u', u'my', u'u', u'posted', u'u', u'our', u'u', u'video', u'u', u'your', u'u', u'your', u'u', u'we', u'u', u'are', u'u', u'apple', u'u', u'have', u'u', u'that', u'u', u'be', u'u', u'u', u'u', u'out', u'u', u'full', u'u', u'from', u'u', u'youtube', u'u', u'song', u'u', u'please', u'u', u'buy', u'u', u'us', u'u', u'help', u'u', u'most', u'u', u'last', u'u', u'here', u'u', u'are', u'u', u'that', u'u', u'we', u'u', u'will', u'u', u'has', u'u', u'be', u'u', u'out', u'u', u'your', u'u', u'check', u'u', u'facebook', u'u', u'out', u'u', u'new', u'u', u'check', u'u', u'will', u'u', u'be', u'u', u'facebook', u'u', u'have', u'u', u'are', u'u', u'u', u'u', u'like', u'u', u'be', u'u', u'will', u'u', u'has', u'u', u'that', u'u', u'u', u'u', u'new', u'u', u'facebook', u'u', u'revealed', u'u', u'me', u'u', u'the', u'u', u'u', u'have', u'u', u'are', u'u', u'their', u'u', u'who', u'u', u'some', u'u', u'been', u'u', u'share', u'u', u'guys', u'u', u'through', u'u', u'wish', u'u', u'u', u'u', u'has', u'u', u'that', u'u', u'xbox', u'u', u'now', u'u', u'the', u'u', u'u', u'revealed', u'u', u'says', u'u', u'video', u'u', u'microsoft', u's', u'u', u'u', u'u', u'google', u'u', u'apple', u'u', u'full', u'u', u'read', u'u', u'price', u'u', u'xbox', u'u', u'ebay', u'u', u'nexus', u'u', u'usd', u'u', u'google', u'u', u'nexus', u'u', u'its', u'u', u'u', u'google', u'u', u'nexus', u'u', u'taking', u'u', u'different', u'u', u'launch', u'u', u'tack', u'u', u'u', u'desktop', u'u', u'mac', u'u', u'runs', u'u', u'systems', u'u', u'multiple', u'u', u'operating', u'u', u'moreos', u'u', u'parallels', u'u', u'simultaneously', u'u', u'allaboutgoogle', u'u', u'first', u'u', u'which', u'u', u'android', u'u', u'google', u's', u'u', u'health', u'u', u'platform', u'u', u'googlefit', u'u', u'debuted', u'u', u'wear']

In [149]:
text = [list(gensim.utils.tokenize(block[2].decode('unicode_escape').encode('ascii','ignore'))) for block in sentiment ]
len(text)


Out[149]:
246

In [152]:
#print text[2]
print type(text)
print type(text[2][1])
stopwords = [u'u,',u'facebook', u'm', u'youtube']
text = [ word for word in text if word not in stopwords ]
print type(text)
print type(text[2][1])
t = text[0]
print t
type(t)


<type 'list'>
<type 'unicode'>
<type 'list'>
<type 'unicode'>
[u'u', u'new', u'u', u'facebook', u'u', u'posted', u'u', u'photo', u'u', u'video', u'u', u'youtube', u'u', u'my', u'u', u'from', u'u', u'liked', u'u', u'out', u'u', u'youtube', u'u', u'video', u'u', u'liked', u'u', u'from', u'u', u'amp', u'u', u'my', u'u', u'with', u'u', u'photo', u'u', u'posted', u'u', u'u', u'my', u'u', u'with', u'u', u'youtube', u'u', u'that', u'u', u'your', u'u', u'are', u'u', u'we', u'u', u'apple', u'u', u'video', u'u', u'amp', u'u', u'from', u'u', u'my', u'u', u'buy', u'u', u'song', u'u', u'last', u'u', u'with', u'u', u'please', u'u', u'us', u'u', u'help', u'u', u'most', u'u', u'my', u'u', u'with', u'u', u'amp', u'u', u'apple', u'u', u'out', u'u', u'your', u'u', u'that', u'u', u'we', u'u', u'check', u'u', u'me', u'u', u'apple', u'u', u'with', u'u', u'we', u'u', u'that', u'u', u'my', u'u', u'read', u'u', u'full', u'u', u'price', u'u', u'ebay', u'u', u'are', u'u', u'your', u'u', u'with', u'u', u'apple', u'u', u'amp', u'u', u'are', u'u', u'my', u'u', u'we', u'u', u'be', u'u', u'will', u'u', u'that', u'u', u'amp', u'u', u'with', u'u', u'apple', u'u', u'that', u'u', u'out', u'u', u'my', u'u', u'from', u'u', u'your', u'u', u'check', u'u', u'get', u'u', u'new', u'u', u'out', u'u', u'facebook', u'u', u'check', u'u', u'amp', u'u', u'my', u'u', u'posted', u'u', u'our', u'u', u'video', u'u', u'your', u'u', u'your', u'u', u'we', u'u', u'are', u'u', u'apple', u'u', u'have', u'u', u'that', u'u', u'be', u'u', u'u', u'out', u'u', u'full', u'u', u'from', u'u', u'youtube', u'u', u'song', u'u', u'please', u'u', u'buy', u'u', u'us', u'u', u'help', u'u', u'most', u'u', u'last', u'u', u'here', u'u', u'are', u'u', u'that', u'u', u'we', u'u', u'will', u'u', u'has', u'u', u'be', u'u', u'out', u'u', u'your', u'u', u'check', u'u', u'facebook', u'u', u'out', u'u', u'new', u'u', u'check', u'u', u'will', u'u', u'be', u'u', u'facebook', u'u', u'have', u'u', u'are', u'u', u'u', u'like', u'u', u'be', u'u', u'will', u'u', u'has', u'u', u'that', u'u', u'u', u'new', u'u', u'facebook', u'u', u'revealed', u'u', u'me', u'u', u'the', u'u', u'have', u'u', u'are', u'u', u'their', u'u', u'who', u'u', u'some', u'u', u'been', u'u', u'share', u'u', u'guys', u'u', u'through', u'u', u'wish', u'u', u'u', u'has', u'u', u'that', u'u', u'xbox', u'u', u'now', u'u', u'the', u'u', u'revealed', u'u', u'says', u'u', u'video', u'u', u'microsoft', u's', u'u', u'u', u'google', u'u', u'apple', u'u', u'full', u'u', u'read', u'u', u'price', u'u', u'xbox', u'u', u'ebay', u'u', u'nexus', u'u', u'usd', u'u', u'google', u'u', u'nexus', u'u', u'its', u'u', u'u', u'google', u'u', u'nexus', u'u', u'taking', u'u', u'different', u'u', u'launch', u'u', u'tack', u'u', u'u', u'desktop', u'u', u'mac', u'u', u'runs', u'u', u'systems', u'u', u'multiple', u'u', u'operating', u'u', u'moreos', u'u', u'parallels', u'u', u'simultaneously', u'u', u'allaboutgoogle', u'u', u'first', u'u', u'which', u'u', u'android', u'u', u'google', u's', u'u', u'health', u'u', u'platform', u'u', u'googlefit', u'u', u'debuted', u'u', u'wear']
Out[152]:
list

In [155]:
#text = [block[2].decode('unicode_escape').encode('ascii','ignore') for block in sentiment ]
#len(text)
def filter_words(text):
    text = [[t.replace("u'","") for t in t] for t in text]
    text = [t.replace("|","") for t in text]
    text = [t.replace("',","") for t in text]
    text = [t.replace("amp","") for t in text]
    text = [t.replace(";","") for t in text]
    text = [t.replace("u\"","") for t in text]
    text = [t.replace("\"","") for t in text]
    text = [t.replace("\'","") for t in text]
    text = [t.replace(",'","") for t in text]
    text = [t.replace("tco,'","") for t in text]

    text = [t.replace("t ,'","") for t in text]
    text = [t.replace("tco,'","") for t in text]
    text = [t.replace("youtube,'","") for t in text]
    text = [t.replace("apple,'","") for t in text]
    text = [t.replace("facebook'","") for t in text]
    text = [t.replace("httpco'","") for t in text]
    text = [t.replace("m'","") for t in text]
    


text = [[filter_words(t) for t in text]


#text = [t.replace(" ","") for t in text]

print text[200]


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-155-da16981de9bf> in <module>()
     24 
     25 
---> 26 text = [filter_words(t) for t in text]
     27 
     28 

<ipython-input-155-da16981de9bf> in filter_words(text)
      4 def filter_words(text):
      5     text = [[t.replace("u'","") for t in t] for t in text]
----> 6     text = [t.replace("|","") for t in text]
      7     text = [t.replace("',","") for t in text]
      8     text = [t.replace("amp","") for t in text]

AttributeError: 'list' object has no attribute 'replace'

In [130]:
text = [t.replace(" ","") for t in text]

In [132]:


In [144]:
len(text)


Out[144]:
246

In [68]:


In [72]:


In [73]:



Out[73]:
[]

In [ ]:


In [56]:
from wordcloud import WordCloud
from os import path
font_path = '/Users/carlyhendrickson/Library/Fonts/SourceCodePro-Light.otf'
import matplotlib.pyplot as plt

In [148]:
wordcloud = WordCloud(font_path, width=700, height=700).generate(str(text[200]))
plt.imshow(wordcloud)
plt.axis("off")
plt.show()

In [50]:


In [87]:
len(text)


Out[87]:
218

In [ ]:


In [82]:
i = 1000
for topic in text:
    i = i + 1
    wordcloud = WordCloud(font_path, width=700, height=700).generate(topic)
    plt.imshow(wordcloud)
    plt.axis("off")
    plt.savefig('foo'+str(i)+'.png', bbox_inches='tight')


---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-82-b4f711a1369c> in <module>()
      5     plt.imshow(wordcloud)
      6     plt.axis("off")
----> 7     plt.savefig('foo'+str(i)+'.png', bbox_inches='tight')

/usr/local/lib/python2.7/site-packages/matplotlib/pyplot.pyc in savefig(*args, **kwargs)
    574 def savefig(*args, **kwargs):
    575     fig = gcf()
--> 576     res = fig.savefig(*args, **kwargs)
    577     draw()   # need this if 'transparent=True' to reset colors
    578     return res

/usr/local/lib/python2.7/site-packages/matplotlib/figure.pyc in savefig(self, *args, **kwargs)
   1468             self.set_frameon(frameon)
   1469 
-> 1470         self.canvas.print_figure(*args, **kwargs)
   1471 
   1472         if frameon:

/usr/local/lib/python2.7/site-packages/matplotlib/backend_bases.pyc in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs)
   2137                     orientation=orientation,
   2138                     dryrun=True,
-> 2139                     **kwargs)
   2140                 renderer = self.figure._cachedRenderer
   2141                 bbox_inches = self.figure.get_tightbbox(renderer)

/usr/local/lib/python2.7/site-packages/matplotlib/backends/backend_agg.pyc in print_png(self, filename_or_obj, *args, **kwargs)
    511 
    512     def print_png(self, filename_or_obj, *args, **kwargs):
--> 513         FigureCanvasAgg.draw(self)
    514         renderer = self.get_renderer()
    515         original_dpi = renderer.dpi

/usr/local/lib/python2.7/site-packages/matplotlib/backends/backend_agg.pyc in draw(self)
    459 
    460         try:
--> 461             self.figure.draw(self.renderer)
    462         finally:
    463             RendererAgg.lock.release()

/usr/local/lib/python2.7/site-packages/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     57     def draw_wrapper(artist, renderer, *args, **kwargs):
     58         before(artist, renderer)
---> 59         draw(artist, renderer, *args, **kwargs)
     60         after(artist, renderer)
     61 

/usr/local/lib/python2.7/site-packages/matplotlib/figure.pyc in draw(self, renderer)
   1077         dsu.sort(key=itemgetter(0))
   1078         for zorder, a, func, args in dsu:
-> 1079             func(*args)
   1080 
   1081         renderer.close_group('figure')

/usr/local/lib/python2.7/site-packages/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     57     def draw_wrapper(artist, renderer, *args, **kwargs):
     58         before(artist, renderer)
---> 59         draw(artist, renderer, *args, **kwargs)
     60         after(artist, renderer)
     61 

/usr/local/lib/python2.7/site-packages/matplotlib/axes/_base.pyc in draw(self, renderer, inframe)
   2090 
   2091         for zorder, a in dsu:
-> 2092             a.draw(renderer)
   2093 
   2094         renderer.close_group('axes')

/usr/local/lib/python2.7/site-packages/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     57     def draw_wrapper(artist, renderer, *args, **kwargs):
     58         before(artist, renderer)
---> 59         draw(artist, renderer, *args, **kwargs)
     60         after(artist, renderer)
     61 

/usr/local/lib/python2.7/site-packages/matplotlib/image.pyc in draw(self, renderer, *args, **kwargs)
    367                               " correctly with this backend.")
    368 
--> 369             im = self.make_image(renderer.get_image_magnification())
    370             if im is None:
    371                 return

/usr/local/lib/python2.7/site-packages/matplotlib/image.pyc in make_image(self, magnification)
    629         im.apply_scaling(rx*sx, ry*sy)
    630         im.resize(int(widthDisplay+0.5), int(heightDisplay+0.5),
--> 631                   norm=self._filternorm, radius=self._filterrad)
    632         return im
    633 

KeyboardInterrupt: