小编gdo*_*371的帖子

如何向tweepy模块添加位置过滤器

我发现下面这段代码非常适合让我在Python Shell中查看twitter firehose的标准1%:

import sys
import tweepy

consumer_key=""
consumer_secret=""
access_key = ""
access_secret = "" 


auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)


class CustomStreamListener(tweepy.StreamListener):
    def on_status(self, status):
        print status.text

    def on_error(self, status_code):
        print >> sys.stderr, 'Encountered error with status code:', status_code
        return True # Don't kill the stream

    def on_timeout(self):
        print >> sys.stderr, 'Timeout...'
        return True # Don't kill the stream

sapi = tweepy.streaming.Stream(auth, CustomStreamListener())
sapi.filter(track=['manchester united'])
Run Code Online (Sandbox Code Playgroud)

如何添加过滤器以仅解析特定位置的推文?我见过人们将GPS添加到其他与Twitter相关的Python代码中,但我无法在Tweepy模块中找到任何特定于sapi的内容.

有任何想法吗?

谢谢

python twitter tweepy

21
推荐指数
2
解决办法
3万
查看次数

无法导入requests.packages.urllib3.util'重试'

我在Windows 8上使用Python 2.7 64位.我安装了Requests 2.3版.我试图运行此import语句作为在我的代码中引入重试次数的一部分:

from requests.packages.urllib3.util import Retry
Run Code Online (Sandbox Code Playgroud)

我也安装了urllib3(我刚刚通过Pip安装了它).我收到错误消息:

Traceback (most recent call last):
  File "C:\Python27\counter.py", line 3, in <module>
    from requests.packages.urllib3.util import Retry
ImportError: cannot import name Retry
Run Code Online (Sandbox Code Playgroud)

谁能告诉我为什么会这样?有没有其他依赖我不知道成功运行这行代码?

谢谢

python urllib3 python-requests

12
推荐指数
2
解决办法
1万
查看次数

AttributeError:解析JSON字典值时,'unicode'对象没有属性'values'

我有以下JSON字典:

{
 u'period': 16, u'formationName': u'442', u'formationId': 2, 
 u'formationSlots': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 0, 0, 0, 0, 0, 0], 
 u'jerseyNumbers': [1, 20, 3, 15, 17, 5, 19, 6, 18, 25, 10, 2, 4, 12, 16, 22, 24, 
                    34], 
 u'playerIds': [23122, 38772, 24148, 39935, 29798, 75177, 3860, 8505, 
               26013, 3807, 34693, 18181, 4145, 23446, 8327, 107395, 29762, 254558], 
 u'captainPlayerId': 29798, 
 u'startMinuteExpanded': 0, 
 u'endMinuteExpanded': 82, 
 u'formationPositions': [{u'horizontal': 5.0, u'vertical': 0.0}, 
     {u'horizontal': 1.0, u'vertical': 2.5}, …
Run Code Online (Sandbox Code Playgroud)

python json dictionary

11
推荐指数
1
解决办法
7万
查看次数

使用re.findall()替换所有匹配项

使用re.findall()我已经设法返回字符串中的正则表达式的多个匹配.但是我返回的对象是字符串中的匹配列表.这不是我想要的.

我想要的是用其他东西替换所有匹配.我尝试使用类似于在re.sub中使用的类似语法来执行此操作:

import json
import re

regex = re.compile('([a-zA-Z]\"[a-zA-Z])', re.S)

filepath = "C:\\Python27\\Customer Stuff\\Austin Tweets.txt"

f = open(filepath, 'r')
myfile = re.findall(regex, '([a-zA-Z]\%[a-zA-Z])', f.read())
print myfile
Run Code Online (Sandbox Code Playgroud)

但是,这会产生以下错误:

Traceback (most recent call last):
  File "C:/Python27/Customer Stuff/Austin's Script.py", line 9, in <module>
    myfile = re.findall(regex, '([a-zA-Z]\%[a-zA-Z])', f.read())
  File "C:\Python27\lib\re.py", line 177, in findall
    return _compile(pattern, flags).findall(string)
  File "C:\Python27\lib\re.py", line 229, in _compile
    bypass_cache = flags & DEBUG
TypeError: unsupported operand type(s) for &: 'str' and 'int'
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮助我在最后一点语法中我需要用原始Python对象中的其他东西替换所有匹配吗?

编辑:

根据收到的评论和答案,这里是我试图将一个正则表达式与另一个正则表达式:

import …
Run Code Online (Sandbox Code Playgroud)

python regex

11
推荐指数
2
解决办法
1万
查看次数

TypeError:'datetime.datetime'对象不可调用

我有一些Python代码遍历两个开始日期之间的所有日子.开始日期始终是11月1日,结束日期始终是5月31日.但是,代码会循环使用多年.我的代码如下:

import time
from datetime import datetime
from datetime import date, timedelta as td

list1 = [2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013]
list2 = [2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014]


for x, y in zip(list1, list2):
    print "list1 - " + str(x)
    print "list2 - " + str(y)


    d1 = date(x,11,01)
    d2 = date(y,5,31)

    delta = d2 - d1



    for i in range(delta.days + 1):

        time1 =  str(d1 + td(days=i))
        time2 = time1.split("-", 1)[0]
        time3 = time1.split("-", -1)[1]
        time4 = time1.rsplit("-", 1)[-1]

        time2 = int(time2)
        time3 = int(time3)
        time4 = …
Run Code Online (Sandbox Code Playgroud)

python time

9
推荐指数
1
解决办法
3万
查看次数

将错误打印到屏幕但继续执行代码

我有一些代码可以遍历一系列 URL。如果由于其中一个 URL 不包含有效的 JSON 正文而导致我的代码出现错误,我希望将生成的错误打印到屏幕上,但随后代码会移至下一次迭代。我的代码的一个简单版本是:

for a in myurls:

    try:

        #mycode

    except Exception as exc:

        print traceback.format_exc()
        print exc
        pass
Run Code Online (Sandbox Code Playgroud)

但是,这会将错误打印到屏幕并结束代码的执行。有没有办法通过移动到“for”循环的下一次迭代来使错误继续执行?

python error-handling exception

8
推荐指数
1
解决办法
8733
查看次数

在For循环中迭代两个范围

我有几个简单的循环,如下所示:

for i in range (30, 52):

    #do some stuff here

for i in range (1, 18):

    #do some more stuff
Run Code Online (Sandbox Code Playgroud)

我想要的是使用顺序语法将它压缩成一个循环:

for i in range((30, 52), (1, 18):

    #do some stuff
Run Code Online (Sandbox Code Playgroud)

我意识到语法不起作用,但这是我需要的基本概念.我见过人们使用zip来同时迭代两个范围,但这不是我需要的.

有任何想法吗?

python

8
推荐指数
2
解决办法
1万
查看次数

使用Python Scrapy时HTTP 403响应

我在Windows Vista 64位上使用Python.org版本2.7 64位.我一直在测试以下Scrapy代码,以递归方式抓取网站www.whoscored.com上的所有页面,这是用于足球统计:

from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
from scrapy.item import Item
from scrapy.spider import BaseSpider
from scrapy import log
from scrapy.cmdline import execute
from scrapy.utils.markup import remove_tags


class ExampleSpider(CrawlSpider):
    name = "goal3"
    allowed_domains = ["whoscored.com"]
    start_urls = ["http://www.whoscored.com/"]
    rules = [Rule(SgmlLinkExtractor(allow=()), 
                  follow=True),
             Rule(SgmlLinkExtractor(allow=()), callback='parse_item')
    ]
    def parse_item(self,response):
        self.log('A response from %s just arrived!' % response.url)
        scripts = response.selector.xpath("normalize-space(//title)")
        for scripts in scripts:
            body = response.xpath('//p').extract()
            body2 = "".join(body)
            print remove_tags(body2).encode('utf-8') …
Run Code Online (Sandbox Code Playgroud)

python http scrapy

7
推荐指数
2
解决办法
1万
查看次数

没有名为 googleapiclient.discovery 的模块

我一直在寻找实现我在网上找到的示例 Python 脚本,以允许我按照此处的 GitHub 链接与 YouTube API 进行交互

我遇到的问题是开头的导入语句:

import argparse

from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
Run Code Online (Sandbox Code Playgroud)

在线文档需要以下命令来安装googleapiclient库:

pip install --upgrade google-api-python-client
Run Code Online (Sandbox Code Playgroud)

但是,一旦安装,我仍然收到一个googleapiclient.discovery无法找到的错误。我尝试通过 pip 重新安装,生成了以下命令行输出,表明一切正常:

Requirement already up-to-date: google-api-python-client in g:\python27\lib\site-packages (1.7.4)
Requirement not upgraded as not directly required: httplib2<1dev,>=0.9.2 in g:\python27\lib\site-packages (from google-api-python-client) (0.9.2)
Requirement not upgraded as not directly required: google-auth>=1.4.1 in g:\python27\lib\site-packages (from google-api-python-client) (1.5.0)
Requirement not upgraded as not directly required: google-auth-httplib2>=0.0.3 in g:\python27\lib\site-packages (from google-api-python-client) (0.0.3)
Requirement …
Run Code Online (Sandbox Code Playgroud)

python pip youtube-api kodi

6
推荐指数
1
解决办法
1万
查看次数

“响应对象没有属性‘body’”

我使用以下代码模仿网页上的 XHR 请求,以在屏幕上选择不同的选项卡按钮时更新表对象的内容:

import requests

url = 'http://www.whoscored.com/stageplayerstatfeed/?field=1&isAscending=false&orderBy=Rating&playerId=-1&stageId=9155&teamId=32"'

params = {'d': date.strftime('%Y%m'), 'isAggregate': 'false'}
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36'}

response = requests.get(url, params=params, headers=headers)

fixtures = response.body
#fixtures = literal_eval(response.content)
print fixtures 
Run Code Online (Sandbox Code Playgroud)

这引发了帖子标题中的错误。我猜我需要在语句中以某种方式添加参数“body” requests.get(),但我不确定具体如何添加。有人可以帮忙吗?

谢谢

python xmlhttprequest

5
推荐指数
1
解决办法
1万
查看次数