2011-09-29 3 views
1

저는 파이썬, mongodb 및 pymongo 모듈을 사용하여 스크립트를 작성하여 Twitter API의 특정 측면을 가져 와서 몽고 데이터베이스에 저장하려고합니다. 여러 가지 스크립트를 작성하여 검색 API에 액세스하고 user_timeline에 액세스하는 등의 작업을 수행했습니다. 그러나 필자는 작업하고있는 모든 도구에 대해 알게되었습니다. 이제는 돌아가서보다 효율적으로 작업 할 때입니다. 따라서 지금은 스크립트에 함수와 클래스를 추가하는 중입니다. 여기에 함수 나 클래스없이 내 스크립트 중 하나입니다내 pymongo/twitter 스크립트 기능을 만드는 방법은 무엇입니까?

#!/usr/local/bin/python 

import twitter 
import datetime 
from datetime import date, timedelta, datetime 
import pymongo 
from pymongo import Connection 

# Twitter handle that we are scraping mentions for 
SCREEN_NAME = '@twitterapi' 

# Connect to the database 
connection = Connection() 
db = connection.test  
collection = db.twitterapi_mentions # Change the name of this database 
t = twitter.Twitter(domain='search.twitter.com') 

# Fetch the information from the API 
results = [] 
for i in range(2): 
    i+=1 
    response = t.search(q=SCREEN_NAME, result_type='recent', rpp=100, page=i)['results'] 
    results.extend(response) 

# Create a document in the database for each item taken from the API 
for tweet in results: 
    id_str = tweet['id_str'] 
    twitter_id = tweet['from_user'] 
    tweetlink = "http://twitter.com/#!/%s/status/%s" % (twitter_id, id_str) 
    created_at = datetime.strptime(tweet['created_at'], "%a, %d %b %Y %H:%M:%S +0000") 
    date = created_at.date().strftime("%m/%d/%y") 
    time = created_at.time().strftime("%H:%M:%S") 
    text = tweet['text'] 
    identifier = {'id' : id_str} 
    entries = {'id' : id_str, 'tweetlink' : tweetlink, 'date' : date, 'time' : time, 'text' : text, 'twitter_id':twitter_id } 
    collection.update(identifier, entries, upsert = True) 

이 스크립트는 잘 날 위해 노력하고있다, 그러나 나는 여러 트위터 핸들에 대해 동일한 스크립트를 실행해야합니다. 예를 들어 나는 같은 스크립트를 복사 한 다음 두 줄을 변경합니다 :

SCREEN_NAME = '@cocacola' 

collection = db.cocacola_mentions 

는 따라서 내가 갖는

는 @twitterapi 및 @cocacola 모두에 대해 언급하고있다. 이 기능을 어떻게 기능화 할 수 있는지에 대해 많은 생각을했습니다. 가장 큰 문제는 컬렉션의 이름을 변경하는 방법을 찾는 것입니다. 나는 모든 데이터가 수집 "SCREEN_NAME"에 저장 한 후 위의 스크립트를 사용하는 경우

#!/usr/local/bin/python 

import twitter 
import datetime 
from datetime import date, timedelta, datetime 
import pymongo 
from pymongo import Connection 

def getMentions(screen_name): 

    # Connect to the database 
    connection = Connection() 
    db = connection.test  
    collection = db.screen_name # Change the name of this database 
    t = twitter.Twitter(domain='search.twitter.com') 

    # Fetch the information from the API 
    results = [] 
    for i in range(2): 
     i+=1 
     response = t.search(q=screen_name, result_type='recent', rpp=100, page=i) ['results'] 
     results.extend(response) 

    # Create a document in the database for each item taken from the API 
    for tweet in results: 
     id_str = tweet['id_str'] 
     twitter_id = tweet['from_user'] 
     tweetlink = "http://twitter.com/#!/%s/status/%s" % (twitter_id, id_str) 
     created_at = datetime.strptime(tweet['created_at'], "%a, %d %b %Y %H:%M:%S +0000") 
     date = created_at.date().strftime("%m/%d/%y") 
     time = created_at.time().strftime("%H:%M:%S") 
     text = tweet['text'] 
     identifier = {'id' : id_str} 
     entries = {'id' : id_str, 'tweetlink' : tweetlink, 'date' : date, 'time' : time, 'text' : text, 'twitter_id':twitter_id } 
     collection.update(identifier, entries, upsert = True) 

getMentions("@twitterapi") 
getMentions("@cocacola") 

하지만 난 그것을 통해 전달 된 화면 이름을 저장할 : 예를 들어,이 스크립트를 고려하십시오. 이상적으로, @ twitterapi가 "twitterapi_mentions"컬렉션에 포함되기를 원하고 @cocacola에 대한 언급이 "cocacola_mentions"컬렉션에 포함되기를 바랍니다. 나는 pymongo의 Collection 클래스를 사용하는 것이 대답일지도 모르고 나는 문서를 읽었지만 제대로 작동하지 않는 것 같다고 생각한다. 이 스크립트를 어떻게 효율적으로 만들어야하는지에 대한 다른 제안이 있으면 믿을 수 없을만큼 감사하게 될 것입니다. 그렇지 않으면, 제가 말했듯이, 제가 실수 한 것을 용서해주십시오.

답변

2

사용 getattr 문자열 이름으로 속성을 검색 할 수 있습니다 :

collection = getattr(db, screen_name) 
+0

예. 이것이 내가 필요한 것입니다. 나는 그것을 어떻게 사용할 지 여전히 놀아야한다. – crunkchitis

+0

코드를 보면, 컬렉션을 얻는 곳의 한 줄만 업데이트하는 것처럼 보입니다. 함수에'screen_name' 변수를 넘겨 주므로'getattr'를 통해 적절한 콜렉션을 얻은 후에 나머지 스크립트에 대한 콜렉션을 갖게됩니다. – jdi

0

내가 함께 갈 것 :

collection = db[screen_name] 

내가 더 간단하게 생각합니다.

관련 문제