【问题标题】:Python dictionary: How to check for of a string in a tuple key in order assign the associated valuePython字典:如何检查元组键中的字符串以分配关联值
【发布时间】: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


    【解决方案1】:

    让我分两部分回答,首先是直接回答您的具体问题,然后是我认为可能更简单的方法。

    1.遍历键

    您可以通过my_dict.keys() 获取字典中所有键的列表。在您的示例中,这将产生一个元组列表。您需要遍历该列表并将找到的字符串与每个元组进行比较:

    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_number 里面有你的号码。但这可能不是我会做的。

    2。重构你的月份字典

    相反,我会拆分您的元组,以便每个元素都是字典中自己的键。然后获取给定月份字符串的数字就变成了对字典进行索引的问题,如下所示:

    month_number = month_dict[the_month]
    

    你的字典看起来更像这样:

    month_dict = {"Jan": "01",
                  "January": "01",
                  "Feb": "02",
                  ...
                  "December": "12"}
    

    请注意,如果您得到的字符串不在您的月份字典中,尝试用它索引到字典中将引发异常(有关如何处理这种情况的更多信息,请参阅dict 文档)。

    您还可以查看 datetimecalendar 模块,因为它们可能会为您尝试做的任何事情提供一些帮助。

    【讨论】:

    • 您的第二个选项看起来像是要走的路,但对我提出了问题。什么时候在键中使用元组是有效的?如果你不能轻松地迭代它,它会有什么用途?
    • 这种情况很少见,但如果您的键需要是各种项目的组合,并且每个潜在的组合散列到不同的东西,您可能会这样做。但是你不得不担心元组中元素的顺序,它会变得有点时髦。我并不是说从来没有用例,它只是你不一定会经常遇到的用例。如果你这样做了,你会希望元素的组合才是最重要的,而不是单个元素(即你通常不应该迭代每个单独的键)。
    • 啊,这很有道理。谢谢
    【解决方案2】:

    另一种方法是保持字典简单,只使用元组键中每个项目的最短公共前缀:

    month_dict = {"Jan": "01",
                  "Feb": "02",
                  ...
                  "Dec": "12"}
    

    然后通过截断要转换为对应数字的字符串来检索数字

    print month_dict[the_month[0:3]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-20
      • 2013-09-24
      • 2017-05-21
      • 2019-03-17
      • 2019-05-01
      • 2015-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多