鱼C论坛

 找回密码
 立即注册
查看: 780|回复: 6

[已解决]如何从URL里 提取数字??

[复制链接]
发表于 2019-5-2 11:12:43 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x

我要如何写简洁的代码 才能把链接里的 数值提取出来?


如:

.php?day=1&month=3&year=2019&hour=7
.php?day=28&month=2&year=2019&hour=19

即把链接中的 年-月-日 小时 的值提取出来。

2019-3-1 7
2019-2-28 19

最佳答案
2019-5-2 19:23:03
  1. import re

  2. def fun(str1):
  3.     get = re.findall(r"day=(\d+)&month=(\d+)&year=(\d+?)&hour=(\d+)",str1)[0]
  4.     return "{}-{}-{} {}".format(get[2],get[1],get[0],get[3])



  5. str1 = ".php?day=1&month=3&year=2019&hour=7"
  6. print(fun(str1))
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-5-2 18:30:18 | 显示全部楼层

尝试了下切割了好几次,不简洁

本帖最后由 waletor 于 2019-5-2 18:35 编辑
  1. s=".php?day=28&month=2&year=2019&hour=19"
  2. item=[]
  3. dictx={}
  4. values=s.split("?")[1]
  5. for key_value in values.split('&'):
  6.     item=key_value.split('=')
  7.     dictx[item[0]]=item[1]
  8. print(dictx)
  9. new_s="%s-%s-%s %s"%(dictx['year'],dictx['month'],dictx['day'],dictx['hour'])
  10. print(new_s)
复制代码


https://blog.csdn.net/dingdang1900/article/details/5783173
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-5-2 18:32:29 From FishC Mobile | 显示全部楼层
正则
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-5-2 19:23:03 | 显示全部楼层    本楼为最佳答案   
  1. import re

  2. def fun(str1):
  3.     get = re.findall(r"day=(\d+)&month=(\d+)&year=(\d+?)&hour=(\d+)",str1)[0]
  4.     return "{}-{}-{} {}".format(get[2],get[1],get[0],get[3])



  5. str1 = ".php?day=1&month=3&year=2019&hour=7"
  6. print(fun(str1))
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-5-2 19:28:49 | 显示全部楼层
>>> s=".php?day=28&month=2&year=2019&hour=19"
>>> year=re.findall("year=(\d+)",s)
>>> month=re.findall("month=(\d+)",s)
>>> day=re.findall("day=(\d+)",s)
>>> hour=re.findall("hour=(\d+)",s)
>>> t=''.join(year[0]+'-'+month[0]+'-'+day[0]+" "+hour[0])
>>> print(t)
2019-2-28 19
>>>
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-5-2 21:25:31 | 显示全部楼层
谢谢各位老师
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-5-3 07:00:10 | 显示全部楼层
import re

def getDate(s):
    result = re.findall('\d+', s)
    if result:
        return "{}-{}-{} {}".format(result[2], result[1], result[0], result[3])


s = ".php?day=1&month=3&year=2019&hour=7"
print(getDate(s))
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-3-29 17:02

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表