In [14]:
%matplotlib inline
from pattern.en import sentiment
import matplotlib.pyplot as plt
In [15]:
fileObj = open('booklist.txt', 'r')
fileLines = map(
    lambda x: x.strip(),
    filter(
        lambda x: x,
        fileObj.readlines()
    )
)
fileObj.close()
In [16]:
def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in xrange(0, len(l), n):
        yield l[i:i+n]
In [19]:
def get_sentiment_by_graf(text, chunksize):
    grafs = filter(lambda x: x, text.split('\n'))
    grafChunks = list(chunks(grafs, chunksize))
    grafChunkStrs = map(lambda x: '\n'.join(x), grafChunks)
    sentlist = map(lambda x: sentiment(x)[0], grafChunkStrs)
    return sentlist
In [20]:
bookSentDict = dict()

for filename in fileLines:
    bookObj = open("books/"+filename, 'r')
    bookText = bookObj.read()
    bookObj.close()
    
    bookTitle = filename.rsplit('.', 1)[0]
    bookSentDict[bookTitle] = get_sentiment_by_graf(bookText, 10)
In [21]:
import json

with open('sentiment_by_graf.json', 'w') as outfile:
    json.dump(bookSentDict, outfile)
In [23]:
for key in bookSentDict:
    sentiments = map(lambda x: x, bookSentDict[key])
    
    print key
    
    plt.plot(sentiments)
    plt.ylabel('sentiment')
    plt.xlabel('paragraphs')
    plt.show()
Galapagos
Bluebeard
Breakfast of Champions
Basic Training
Mother Night
Armageddon In Retrospect
Slaughterhouse-Five
Jailbird
Slapstick
Happy Birthday, Wanda June
God Bless You, Dr. Kevorkian
Palm Sunday
We Are What We Pretend to Be
If This Isn't Nice, What Is
Man without a Country, A
Cat's Cradle
While Mortals Sleep
Sirens of Titan, The
Welcome to the Monkey House
2BR02B
Petrified Ants
God Bless You, Mr. Rosewater
Deadeye Dick
Hocus Pocus
Letters
Timequake
Player Piano
Look at the Birdie
Bagombo Snuff Box
In [ ]: