Python 循环搜索无法检测二月号并返回正确的月份
我试图计算正则表达式以确定文件名中的月份,并仅返回月份名称。我的代码如下所示: def月份(名称):Python 循环搜索无法检测二月号并返回正确的月份,python,regex,loops,Python,Regex,Loops,我试图计算正则表达式以确定文件名中的月份,并仅返回月份名称。我的代码如下所示: def月份(名称): 如果重新搜索(”(?我会首先尝试获取文件名中与月份名称对应的部分,然后匹配它: months = {'1': 'January', 'Jan': 'January', '2': 'February', 'Feb': 'February', ...} matcher = re.search('MLV\s.\s(\w+)', name) try: return months[matcher
如果重新搜索(”(?我会首先尝试获取文件名中与月份名称对应的部分,然后匹配它:
months = {'1': 'January', 'Jan': 'January', '2': 'February', 'Feb': 'February', ...}
matcher = re.search('MLV\s.\s(\w+)', name)
try:
return months[matcher.group(1)]
except:
return None
我会尝试一种混合的方法-这里是日历。month_name
是一个常规字典,您可以通过给出与该月份对应的整数来获得月份名称,例如1
表示1
,如果您想要月的简短形式,那么使用calendar.month\u abbr
而不是calendar.month_name
例如calendar.mon_abbr[1]
将给出'Jan'
from dateutil import parser
import calendar,re
txt = """MLV A 1.4.16.pdf
MLV A 2.7.16.pdf
MLV N Jan 2016"""
for x,date,y in re.findall(r'(MLV\s*\w\s*)(.*?)($|.pdf)',txt):
d=parser.parse(date)
print "'{0}' has month {1}".format(date,calendar.month_name[d.month])
输出-
'1.4.16' has month January
'2.7.16' has month February
'Jan 2016' has month January
'1.4.16' == January 2016
'2.7.16' == February 2016
'Jan 2016' == January 2016
re.findall(r'(MLV\s*\w\s*)(.*)($|.pdf),txt)
将返回[('MLV A','1.4.16','.pdf'),('MLV A','2.7.16','.pdf'),('MLV N','2016年1月','')
有关此处使用的正则表达式的详细信息,请参见
更多详细信息(年份)-您也可以添加日期,这里我省略了,因为您的数据没有所有日期-
from dateutil import parser
import re
txt = """MLV A 1.4.16.pdf
MLV A 2.7.16.pdf
MLV N Jan 2016"""
for x,date,y in re.findall(r'(MLV\s*\w\s*)(.*?)($|.pdf)',txt):
d=parser.parse(date)
print "'{0}' == {1} {2}".format(date,d.strftime("%B"),d.strftime("%Y"))
输出-
'1.4.16' has month January
'2.7.16' has month February
'Jan 2016' has month January
'1.4.16' == January 2016
'2.7.16' == February 2016
'Jan 2016' == January 2016
有关strftime格式的详细信息,请参见。非常好!这非常有效,我在程序中将相同的方法应用于日格式和年格式。这压缩了大量重复的代码。非常感谢。
'1.4.16' == January 2016
'2.7.16' == February 2016
'Jan 2016' == January 2016