[英]Why am I getting an IndexError for a (seemingly) properly-split string?
I currently have a script that is supposed to fetch and return the number of clicks a Bit.ly link has. 我目前有一个脚本,该脚本应该获取并返回Bit.ly链接的点击次数。 I start out by gathering and reading the data from a Bitly url, which I appear to be doing correctly.
我首先从Bitly url收集并读取数据,看来我做得正确。
bitly_data = "https://api-ssl.bitly.com/v3/link/clicks?access_token=ACCESS_TOKEN&link=http://bit.ly/"+link
src = urllib2.urlopen(bitly_data)
src = src.read()
When link
is something such as TY8lnd
, src
is a string that looks something like 当
link
是诸如TY8lnd
, src
是一个看起来像这样的字符串
{"status_code": 200, "data": {"units": -1, "tz_offset": -4, "unit": "day", "link_clicks": 535}, "status_txt": "OK"}
{“状态代码”:200,“数据”:{“单位”:-1,“ tz_offset”:-4,“单位”:“天”,“链接点击次数”:535},“状态文本”:“确定”}
I now want to parse this string to get just the numerical value after link_clicks
. 我现在想解析该字符串,以获取
link_clicks
之后的数值。 I figured the best way to do this was by making two splits. 我认为最好的方法是进行两次拆分。
src=src.split('clicks": ')
src = str(src[1])
clicks = src.split('}, "status')
clicks = clicks[0]
When I run this, clicks does, ultimately, equal the correct number and only that. 当我运行此命令时,点击数最终确实等于正确的数字并且只有那个。 However, Terminal returns an IndexError for the line
src = str(src[1])
. 但是,终端对于
src = str(src[1])
行返回IndexError。 I tried getting rid of the str()
but this had no effect. 我试图摆脱
str()
但这没有效果。 An understanding as to why I am getting this error despite the end value being corrected would be greatly appreciated. 尽管最终值已被更正,但我仍然理解为什么仍会收到此错误,将不胜感激。
Here is the Traceback in its entirety: 这是完整的追溯:
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1701, in __call__
return self.wsgi_app(environ, start_response)
File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1689, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1360, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1358, in full_dispatch_request
rv = self.dispatch_request()
File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1344, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/Zach/Dropbox/bitly/bit.py", line 35, in settings
src = str(src[1])
IndexError: list index out of range
Thank you in advance. 先感谢您。
This response is json, as such, decode the json instead of trying to parse the string. 此响应是json,因此,解码json而不是尝试解析字符串。
>>> import json
>>> resp = '{"status_code": 200, "data": {"units": -1, "tz_offset": -4, "unit": "day", "link_clicks": 535}, "status_txt": "OK"}'
>>> resp_object = json.loads(resp)
>>> resp_object and resp_object.get('data', {}).get('link_clicks', 0) or 0
535
src
looks like it's JSON. src
看起来像是JSON。 Why not use the json
module to read it directly? 为什么不使用
json
模块直接读取它?
For whatever reason if you don't want to use json
, then read on: 无论出于何种原因,如果您不想使用
json
,请继续阅读:
The error is caused by you assuming that the substring you split on exists in the string you split, ie that 'clicks": '
is indeed a substring of src
. If this is not the case (as I suspect it isn't when the error is raised), then split
returns a list with only one element in it, and that element is src
. 该错误是由您假设您拆分的子字符串存在于您拆分的字符串中引起的,即
'clicks": '
的确是src
的子字符串。如果不是这种情况(因为我怀疑当错误),然后split
返回仅包含一个元素的列表,该元素为src
。
If you prefer that in this case, that src[1]
should give you an empty string after calling src = src.split('clicks": ')
, then you are better off using str.partition
: 如果在这种情况下,您更喜欢
src[1]
则在调用src = src.split('clicks": ')
之后应该给您一个空字符串,那么最好使用str.partition
:
In [5]: somestr = 'prefixclicks: "suffix'
In [6]: somestr.partition('clicks: "')
Out[6]: ('prefix', 'clicks: "', 'suffix')
In [7]: somestr.partition('clicks: "')[-1]
Out[7]: 'suffix'
In [8]: somestr = 'prefixsuffix'
In [9]: somestr.partition('clicks: "')
Out[9]: ('prefixsuffix', '', '')
In [10]: somestr.partition('clicks: "')[-1]
Out[10]: ''
Hope this helps 希望这可以帮助
you can try this to find out the value of link_clicks
, use ast.literal_eval()
: 您可以尝试使用
ast.literal_eval()
来找出link_clicks
的值:
In [14]: import ast
In [15]: src=`{"status_code": 200, "data": {"units": -1, "tz_offset": -4, "unit": "day", "link_clicks": 535}, "status_txt": "OK"}`
In [16]: d=ast.literal_eval(src)
In [17]: d["data"]["link_clicks"]
Out[17]: 535
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.