在Python中解析日期字符串

evg*_*iuz 4 python string

我该如何重写以下条款:

if u'??????' in date_category['title']:
    month = 1
elif u'???????' in date_category['title']:
    month = 2
elif u'?????' in date_category['title']:
    month = 3
elif u'??????' in date_category['title']:
    month = 4
elif u'???' in date_category['title']:
    month = 5
elif u'????' in date_category['title']:
    month = 6
elif u'????' in date_category['title']:
    month = 7
elif u'???????' in date_category['title']:
    month = 8
elif u'????????' in date_category['title']:
    month = 9
elif u'???????' in date_category['title']:
    month = 10
elif u'??????' in date_category['title']:
    month = 11
elif u'???????' in date_category['title']:
    month = 12
Run Code Online (Sandbox Code Playgroud)

它看起来很难看.

Mar*_*cin 7

要解决此问题,请使用python datetime模块解析日期信息.它支持语言环境,并将对此进行排序.如果基因形式确实是问题,那么只需将这些形式映射到dative,然后映射回输出.

要回答你的实际问题 -

考虑您正在将数据与整数配对.如果您可以将数据转换为格式(month, integer),则可以使用数据驱动代码.

for (n, month) in enumerate(u'??????, feb, mar, apri, may, jun, jul, aug, sep, oct, nov, ???????'.split(', '), 1):# the parameter 1 specifies to start counting from 1. h/t @san4ez
    if month in date_category['title']: return n
Run Code Online (Sandbox Code Playgroud)