안녕하세요, "생각의 웹"입니다.


이번에는 갖은 시행 착오 끝에 설치를 완료한 NLTK를 활용해 IoT로 검색해 얻은 600 건의 트윗의 내용을 

word cloud로 만든 사례를 소개하고자 합니다.





이를 위해 python의 tweeter module을 이용해 아래와 같이 코딩했습니다.


# coding=UTF-8

import os.path
import json
import sys
import nltk

import collecttweets
import jsonreader

from collections import Counter
from prettytable import PrettyTable

##
# Get tweets from JSON dump file or twitter API
#
def get_tweets() :
	file_path = "tweets.json"
	if os.path.exists(file_path) :
		return jsonreader.read(file_path)
	else:
		return collecttweets.search_tweets_by_hash_tag('IoT', 5, 100)

##
# Tokenize all tweet messages
#
def tokenize(statuses) :
    status_texts = [ status['text']
        for status in statuses ]

    tokens = []
    for s in status_texts:
        tokens += nltk.tokenize.word_tokenize(s.lower())
    return tokens

##
# Get stemmed list
#
def get_stemmed_list(tokens) :
    from nltk.corpus import stopwords
    stop_words = stopwords.words('english') + ['.', ',', '--', '\'s', '?', ')', '(', ':', '\'', '\'re', '"',
        '-', '}', '{', u'—', 'rt', 'http', 't', 'co', '@', '#', '/', u'…',
        u'#', u';',  u'amp', u't', u'co', u']', u'[', u'`', u'`', u'&', u'|', u'\u265b', u"''", u'$', u'//', u'/'
        u'via',  u'...', u'!', u'``', u'http']

    from nltk.stem import PorterStemmer
    stemmer = PorterStemmer()
    stemmed = []
    for token in tokens:
        # try to decode token
        try:
            decoded = token.decode('utf8')
            #print decoded
        except UnicodeError:
            decoded = token

        if decoded is '' or decoded in stop_words:
            continue
        stem = stemmer.stem(decoded)
        #print stem
        # Skip a few text. I don't know why stopwords are not working :(
        #skip t.co things
        if stem.find(u't.co') > 0:
            continue
        #skip http things
        elif stem.find(u'http') >= 0:
            #print stem
            continue
        else:
            stemmed.append(stem)
    return stemmed

def write_file(filename, lines) :
    f = file(filename, 'w')
    for word in lines:
        try:
            f.write(word.encode('utf-8') + '\n')
        except UnicodeEncodeError, e:
            print 'Encoding error ' + word + '\n'
    f.close()

# Simple test
statuses = get_tweets()
tokens = tokenize(statuses)
print tokens
stemmed = get_stemmed_list(tokens)
print stemmed
write_file('word.txt', stemmed)



간략히 설명하면 

1) twitter API로 관심주제 (저 같은 경우는 IoT)로 tweet를 수집한다. 

2) tweet의 내용을 token으로 쪼개 모은다.

3) stemmer로 token를 분석해 불필요한 단어들을 제거한다. 

4) 남은 word들을 파일로 출력한다. 만들어진 word.txt를 아래 사이트에서 word cloud로 만들면 앞서 그림과 같이 예쁜 그림을 얻을 수 있습니다. 

(silverlight로 제작된 사이트니 IE에서 접속하는 걸 추천합니다 ;-) ) 

http://www.tagxedo.com/app.html 


이상입니다. 


감사합니다.

+ Recent posts