Skip to content

Instantly share code, notes, and snippets.

@timmyshen
Forked from anonymous/tweet_sentiment.py
Created July 9, 2014 03:32
Show Gist options
  • Save timmyshen/77f2ea494ccb9190c232 to your computer and use it in GitHub Desktop.
Save timmyshen/77f2ea494ccb9190c232 to your computer and use it in GitHub Desktop.

Revisions

  1. @invalid-email-address Anonymous created this gist Jul 9, 2014.
    54 changes: 54 additions & 0 deletions tweet_sentiment.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,54 @@
    import sys
    import json

    def hw():
    print 'Hello, world!'

    def lines(fp):
    print str(len(fp.readlines()))

    def main():
    sent_file = open(sys.argv[1])
    tweet_file = open(sys.argv[2])
    hw()
    lines(sent_file)
    lines(tweet_file)


    def make_afinn_dict(afinn_file):
    with open(afinn_file) as f:
    # lines -- list of strings
    lines = f.readlines()
    linecells = [convert_line(line) for line in lines]
    return dict(linecells)


    def convert_line(line):
    word, score_str = line.rstrip().split('\t')
    score = int(score_str)
    return [word, score]


    def make_tweet_json(input_file):
    with open(input_file) as f:
    lines = f.readlines()
    return [make_tweet(line) for line in lines]


    def make_tweet(line):
    return json.loads(line)

    def calc_score(afinn_dict, text):
    words = text.split()
    words_scores = [afinn_dict[word] if afinn_dict.has_key(word) else 0 for word in words]
    return sum(words_scores)

    if __name__ == '__main__':
    afinn_file = sys.argv[1]
    input_file = sys.argv[2]
    afinn_dict = make_afinn_dict(afinn_file)
    tweets = make_tweet_json(input_file)
    scores = [calc_score(afinn_dict, tweet['text']) if tweet.has_key('text') else 0 for tweet in tweets]
    for score in scores:
    print score