Python字典:如何检查元组键中字符串的大小,以便分配相关值
作为一个Pythonewbie,我正在尝试创建一个函数,该函数将根据字典中的单词检查字符串数月,并提取该月的值。本质上,我不知道如何迭代元组作为字典中的键。见下文:Python字典:如何检查元组键中字符串的大小,以便分配相关值,python,python-2.7,Python,Python 2.7,作为一个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 T
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()
让我分两部分回答,首先是对你具体问题的直接回答,然后是我认为可能更简单的方法 1。迭代键 通过执行
my_dict.keys()
,可以获得dict中所有键的列表。在您的示例中,这将生成一个元组列表。您需要迭代该列表,并将找到的字符串与每个元组进行比较:
key_list = month_dict.keys()
month_number = None
for key_tuple in key_list:
if the_month in key_tuple:
month_number = month_dict[key_tuple]
break
现在month\u number
中有您的号码。但我可能不会这么做
2。重组您的月报表
相反,我会拆分元组,这样每个元素在dict中都是自己的键。然后获取给定月份字符串的数字就变成了在dict中建立索引的问题,如下所示:
month_number = month_dict[the_month]
month_dict = {"Jan": "01",
"January": "01",
"Feb": "02",
...
"December": "12"}
你的口述看起来更像这样:
month_number = month_dict[the_month]
month_dict = {"Jan": "01",
"January": "01",
"Feb": "02",
...
"December": "12"}
请注意,如果您得到一个不在您的月份dict中的字符串,尝试将其索引到dict中将引发异常(有关如何处理此场景的更多信息,请参阅文档)
您还可以查看和模块,因为它们可能会为您尝试执行的任何操作提供一些帮助。另一种方法是保持字典的简单性,只使用元组键中每个项的最短公共前缀:
month_dict = {"Jan": "01",
"Feb": "02",
...
"Dec": "12"}
然后通过截断要转换为相应数字的字符串来检索数字
print month_dict[the_month[0:3]]
你的第二个选择看起来是可行的,但这给我提出了一个问题。在密钥中使用元组何时会有效?如果您不能轻松地对其进行迭代,那么它有什么用途呢?这很少见,但是如果您的键需要是各种项目的组合,并且每个潜在的组合都会散列到不同的内容,那么您可以这样做。但是你不得不担心元组中元素的顺序,它会变得有点古怪。我不是说没有用例,只是你不一定会经常遇到。如果你这么做了,你会希望元素的组合是重要的,而不是单个元素(也就是说,你通常不应该迭代每个单独的键)。啊,这是有意义的。谢谢