从python中的字符串中提取年份 [英] Extracting year from string in python

查看:325
本文介绍了从python中的字符串中提取年份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何解析 foll.在python中提取年份:

How can I parse the foll. in python to extract the year:

'years since 1250-01-01 0:0:0'

答案应该是 1250

推荐答案

有很多种方法可以做到,这里有几个选项:

There are all sorts of ways to do it, here are several options:

  • dateutil parser in a "fuzzy" mode:

In [1]: s = 'years since 1250-01-01 0:0:0'

In [2]: from dateutil.parser import parse

In [3]: parse(s, fuzzy=True).year  # resulting year would be an integer
Out[3]: 1250

  • 带有捕获组的正则表达式:

    In [2]: import re
    
    In [3]: re.search(r"years since (\d{4})", s).group(1)
    Out[3]: '1250'
    

  • 先用since"再用破折号分割:

  • splitting by "since" and then by a dash:

    In [2]: s.split("since", 1)[1].split("-", 1)[0].strip()
    Out[2]: '1250'
    

  • 或者甚至可能被第一个破折号分割并切片第一个子字符串:

  • or may be even splitting by the first dash and slicing the first substring:

    In [2]: s.split("-", 1)[0][-4:]
    Out[2]: '1250'
    

  • 最后两个涉及更多的移动部分",可能不适用,具体取决于输入字符串的可能变化.

    The last two involve more "moving parts" and might not be applicable depending on possible variations of the input string.

    这篇关于从python中的字符串中提取年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆