2012-04-02 61 views
4

我有這樣一小段代碼,基本上需要一個列表並運行一個循環,對列表中的每個項目運行鍼對twitter的搜索查詢。我想在列表中每個項目是一個集合名稱,但由於某種原因,我無法弄清楚如何使db<collection_name_variable>.insert(post)>實際工作:在db插入命令中收集名稱的Python/Pymongo變量

我得到一個錯誤:

TypeError: unsupported operand type(s) for +: 'Database' and 'str'

我知道這是可能非常基本,但我只是在學習。

from twython import Twython 
from pymongo import * 

conn = Connection('localhost') 
db = conn.nosqltweets 
twitter = Twython() 

types = ['mongodb', 'cassandra', 'couchdb'] 

for nosql in types: 
    search_results = twitter.searchTwitter(q=nosql, rpp="100") 
    for tweet in search_results["results"]: 
     from_user = tweet['from_user'].encode('utf-8') 
     text = tweet['text'] 
     created_at = tweet['created_at'] 
     id_str = tweet['id_str'] 
     post = { 'id_str': id_str, 'from_user': from_user, 'created_at': created_at } 
     insert = db + nosql + ".insert(post)" 
     insert 
+1

您嘗試添加類型 「數據庫」(DB)和 「字符串」 使用「(NoSQL的)的/串連對象+ 「運營商。 – Fenikso 2012-04-02 17:50:03

+0

Fenikso yep,實際上令人驚訝,因爲它是我明白的問題,只是不明白如何解決它。感謝您的評論! – 2012-04-02 19:29:19

+0

@Ajj你可以通過使用反引號(')來避免內聯代碼的調整。 – 2012-04-03 07:10:51

回答

10

替換:

insert = db + nosql + ".insert(post)" 
insert 

有:

db[nosql].insert(post) 
+0

對不起diliop,沒有工作,我會回答我自己的問題,但它不會讓我在這裏是我所做的: 我用getattr(db,nosql) collection = getattr(db,nosql) collection.insert(post) – 2012-04-02 19:31:18

+3

除非上面的代碼中缺少某些東西,否則這應該起作用。 db的類型爲'',你可以同時使用點符號,即'db.couchdb'或'dict'成員訪問,即'db ['couchdb']'來獲得' '你可以調用'insert()'。 – diliop 2012-04-02 20:16:34

+0

diliop你是對的,顯然我沒有嘗試你發佈的內容是否正確,因爲我今天晚上再次嘗試了它,它工作正常!謝謝!! – 2012-04-03 01:26:35