在以下情况下,如何让 twitter API 正常工作?发生这个问题是因为我不小心使用了错误的模块。如果是这样,我该如何解决?
我一直在做哈佛的 CS109,第 1 讲 ipython 笔记本——所有其他的例子都对我有用,除了这个。一切都是几个月前使用 anaconda 安装的。我想我无法让 ipython 使用正确的库。
我在 ipython 中输入了这个:
!pip install python-twitter //I added this later to try to identify where it was breaking
!pip install twitter //I added this later to try to identify where it was breaking
import twitter
print twitter //I added this later to help to identify where it was breaking
## define the necessary keys
cKey = "<myKeyIsHere>"
cSecret = "<mySecretIsHere>"
aKey = "<myAccessKeyIsHere>"
aSecret = "<myAccessSecretIsHere>"
## create the api object with the twitter-python library
api = twitter.Api(consumer_key=cKey, consumer_secret=cSecret, access_token_key=aKey, access_token_secret=aSecret)
这就是我得到的:
Requirement already satisfied (use --upgrade to upgrade): python-twitter in /Applications/anaconda/lib/python2.7/site-packages
Requirement already satisfied (use --upgrade to upgrade): requests in /Applications/anaconda/lib/python2.7/site-packages (from python-twitter)
Requirement already satisfied (use --upgrade to upgrade): requests-oauthlib in /Applications/anaconda/lib/python2.7/site-packages (from python-twitter)
Requirement already satisfied (use --upgrade to upgrade): oauthlib>=0.6.2 in /Applications/anaconda/lib/python2.7/site-packages (from requests-oauthlib->python-twitter)
Requirement already satisfied (use --upgrade to upgrade): twitter in /Applications/anaconda/lib/python2.7/site-packages
<module 'twitter' from '/Applications/anaconda/lib/python2.7/site-packages/twitter/__init__.pyc'>
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-17-8bddd9593b3f> in <module>()
10
11 ## create the api object with the twitter-python library
---> 12 api = twitter.Api(consumer_key=cKey, consumer_secret=cSecret, access_token_key=aKey, access_token_secret=aSecret)
AttributeError: 'module' object has no attribute 'Api'
到目前为止,我已经完成了以下操作:
- 我开始时遇到了完全相同的错误(尽管没有安装消息)。最初,我认为错误是因为我没有安装正确的库而引发的。从终端,我运行了“pip install twitter”,但没有解决它,因为......我认为它不是正确的库。我应该使用 python-twitter。我误解了错误是什么。从那以后我运行了“pip uninstall twitter”,发现它和 python-twitter 之间存在依赖关系,并通过 ipython 重新安装了它。
- 我在终端中使用了“which”来检查我的 python 和 ipython 是否在同一个位置——它们是。
- 回到 ipython,我在“import twitter”之后使用了“print twitter”,以查看 ipython 引用的是哪个对象。它向我展示了一个 twitter 包,而不是 python-twitter 包。
- 我一直在阅读 stackoverflow 并找到的答案表明我可能通过运行“pip install twitter”和“pip uninstall twitter”而混淆了 ipython,并认为我一定是在以某种方式使用不同的安装。
- 为了弄清楚这一点,并确保我在正确的位置并且不会误用它,我从 ipython 运行了 '!pip install python-twitter' 和 '!pip install twitter'。我推断它们已正确安装,因为消息说要求已经满足,并且它们都在 anaconda 安装中。那正确吗?
我认为,如果我的 ipython 使用正确的库,那么我的模块对象将具有“Api”方法,因为 python-twitter 的文档(https://code.google.com/p/python-twitter/)有这个例子:
>>> import twitter
>>> api = twitter.Api()
如果有人能告诉我哪里出错了,我将不胜感激。
谢谢。