gpt4 book ai didi

python - 从字符串中解析值

转载 作者:行者123 更新时间:2023-11-30 23:33:42 27 4
gpt4 key购买 nike

我有:

url = 'http://example.com/json?key=12345&lat=52.370216&lon=4.895168&status=upcoming&radius=20&offset=0'

如何解析参数radius的值20

我认为urlparse.parse_qs()不可能,不是吗?还有比使用正则表达式更好的方法吗?

最佳答案

是的,使用parse_qs() :

Parse a query string given as a string argument (data of type application/x-www-form-urlencoded). Data are returned as a dictionary. The dictionary keys are the unique query variable names and the values are lists of values for each name.

>>> from urlparse import parse_qs
>>> url = 'http://example.com/json?key=12345&lat=52.370216&lon=4.895168&status=upcoming&radius=20&offset=0'
>>> parse_qs(url)['radius'][0]
'20'

UPD:正如 @DanielRoseman 指出的(参见评论),您应该首先通过 urlparse 传递 url:

>>> from urlparse import parse_qs, urlparse
>>> parse_qs(urlparse(url).query)['radius'][0]
'20'

关于python - 从字符串中解析值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18612307/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com