我是Python的新手。我正在写一个简单的课,但我有一个错误。
我的课程:
import config # Ficheiro de configuracao
import twitter
import random
import sqlite3
import time
import bitly_api #https://github.com/bitly/bitly-api-python
class TwitterC:
def logToDatabase(self, tweet, timestamp):
# Will log to the database
database = sqlite3.connect('database.db') # Create a database file
cursor = database.cursor() # Create a cursor
cursor.execute("CREATE TABLE IF NOT EXISTS twitter(id_tweet INTEGER AUTO_INCREMENT PRIMARY KEY, tweet TEXT, timestamp TEXT);") # Make a table
# Assign the values for the insert into
msg_ins = tweet
timestamp_ins = timestamp
values = [msg_ins, timestamp_ins]
# Insert data into the table
cursor.execute("INSERT INTO twitter(tweet, timestamp) VALUES(?, ?)", values)
database.commit() # Save our changes
database.close() # Close the connection to the database
def shortUrl(self, url):
bit = bitly_api.Connection(config.bitly_username, config.bitly_key) # Instanciar a API
return bit.shorten(url) # Encurtar o URL
def updateTwitterStatus(self, update):
short = self.shortUrl(update["url"]) # Vou encurtar o URL
update = update["msg"] + short['url']
# Will post to twitter and print the posted text
twitter_api = twitter.Api(consumer_key=config.twitter_consumer_key,
consumer_secret=config.twitter_consumer_secret,
access_token_key=config.twitter_access_token_key,
access_token_secret=config.twitter_consumer_secret)
status = twitter_api.PostUpdate(update) # Fazer o update
msg = status.text # Vou gravar o texto enviado para a variavel 'msg'
# Vou gravar p a Base de Dados
self.logToDatabase(msg, time.time())
print msg
x = TwitterC()
x.updateTwitterStatus([{"url": "http://xxxx.com/?cat=31", "msg": "See some strings..., "}])
错误是:
Traceback (most recent call last):
File "C:\Documents and Settings\anlopes\workspace\redes_soc\src\twitterC.py", line 42, in <module>
x.updateTwitterStatus([{"url": "http://xxxx.com/?cat=31", "msg": "See some strings..., "}])
File "C:\Documents and Settings\anlopes\workspace\redes_soc\src\twitterC.py", line 28, in updateTwitterStatus
short = self.shortUrl(update["url"]) # Vou encurtar o URL
TypeError: list indices must be integers, not str
有关如何解决问题的任何线索?
最诚挚的问候,
答案 0 :(得分:1)
看起来你对updateTwitterStatus的调用只需要丢失方括号:
x.updateTwitterStatus({"url": "http://xxxx.com/?cat=31", "msg": "See some strings..., "})
您传递的是包含单个词典元素的列表。看起来这个方法只需要一个带有“url”和“msg”键的字典。
在Python中,{...}
创建一个字典,[...]
创建一个列表。
答案 1 :(得分:0)
错误消息告诉您需要知道的一切。它说“列表索引必须是整数,而不是str”,并指向代码short = self.shortUrl(update["url"])
。很明显,python解释器认为update
是一个列表,"url"
不是列表中的有效索引。
由于update
作为参数传入,我们必须查看它的来源。它看起来像[{...}]
,这意味着它是一个包含单个字典的列表。大概你打算只传递字典,所以在调用x.updateTwitterStatus
调试的第一个规则是假设错误消息是正确的,你应该从字面上理解它。