【发布时间】:2014-05-20 04:22:23
【问题描述】:
一个 Pythonewbie,我正在尝试创建一个函数,该函数将根据字典单词检查字符串几个月并提取该月的值。本质上,我不确定如何迭代用作字典中的键的元组。见下文:
import re
def main():
'''A script to convert a date cluster in word form to date in number form'''
the_clipbrd = '''November 30, 2014 Logo mugs ordered Tom
March 4, 2014 A bag of tricks Fred'''
the_result = grind_wordgorian(the_clipbrd)
def grind_wordgorian(the_lines):
'''Process date formats that have months in English clusters
separated by periods, dashs, or slashes'''
month_dict = {
('January','Jan.','Jan'):'01',
('February','Feb.','Feb'):'02',
('March','Mar.','Mar'):'03',
('April','Apr.','Apr'):'04',
('May'):'05',
('June','Jun.','Jun'):'06',
('July','Jul.','Jul'):'07',
('August','Aug.','Aug'):'08',
('September','Sept.','Sept', 'Sep'):'09',
('October','Oct.','Oct'):'10',
('November','Nov.','Nov'):'11',
('December','Dec.','Dec'):'12'
}
for the_line in the_lines.splitlines():
## Find a word cluster which might have month word followed by a date and a year.
some_dates = re.findall(r'\s?([\w.]{3,9})[-\./ ](\d{1,2}),? ?(\d{0,4})(\s?)', the_line)
## go through everything found
for the_date_cluster in some_dates:
## Check to see if there is a month in word form
the_month = the_date_cluster[0]
## Hey this works!
print 'The ' + the_month
## Check to see if the first cluster is a month in word form
## return the correct month in number form .
## Wait, how do I do that?
## Ensures main is called if it the main script
if __name__ == '__main__':
main()
【问题讨论】:
标签: python python-2.7