2012-12-29 128 views
-2

我想解决这个问题。这是问题和代码。 #写一个过程date_converter,它需要两个输入。第一个是 #字典,第二个是字符串。该字符串是格式月/日/年的 #中的有效日期。该程序应返回 #表格中写入的日期。 #例如,如果 #词典是英文,python密钥错误信息

english = {1:"January", 2:"February", 3:"March", 4:"April", 5:"May", 
6:"June", 7:"July", 8:"August", 9:"September",10:"October", 
11:"November", 12:"December"} 

# then "5/11/2012" should be converted to "11 May 2012". 
# If the dictionary is in Swedish 

swedish = {1:"januari", 2:"februari", 3:"mars", 4:"april", 5:"maj", 
6:"juni", 7:"juli", 8:"augusti", 9:"september",10:"oktober", 
11:"november", 12:"december"} 

# then "5/11/2012" should be converted to "11 maj 2012". 

# Hint: int('12') converts the string '12' to the integer 12. 

def date_converter(dic, n): 
    theSplit = n.split("/") 
    a = theSplit[0] 
    b = theSplit[1] 
    c = theSplit[2] 
    if a in dic: 
     return b + " " + dic[theM] + " " + c 
    else: 
     return None 

print date_converter(english, '5/11/2012') 
#>>> 11 May 2012 

print date_converter(english, '5/11/12') 
#>>> 11 May 12 

print date_converter(swedish, '5/11/2012') 
#>>> 11 maj 2012 

print date_converter(swedish, '12/5/1791') 
#>>> 5 december 1791 

输出: 无 无 无 无 注销

[工艺补]

什么是问题。

回答

0

在你的字典中,键是数字(不是字符串)。

def date_converter(dic, n): 
    theSplit = n.split("/") 
    a = theSplit[0] 
    b = theSplit[1] 
    c = theSplit[2] 
if int(a) in dic: 
    return b + " " + dic[int(a)] + " " + c 
else: 
    return None 
+0

谢谢。我不知道你必须指定它是一个整数。 – user1937034

1

你不必在这里重新发明轮子,因为Python自带的“batteries included”。 :-)

使用datatime模块。

In [23]: import datetime 

In [24]: d = datetime.date(2012, 5, 11) 

In [25]: d.strftime('%d %b %Y') 
Out[25]: '11 May 2012' 

strftime方法将在区域设置中输出正确的月份名称。

您可以使用locale.setlocale()来设置区域设置。因此对于瑞典语:

In [30]: locale.normalize('sv') 
Out[30]: 'sv_SE.ISO8859-1' 

In [31]: locale.setlocale(locale.LC_ALL, locale.normalize('sv')) 
Out[31]: 'sv_SE.ISO8859-1' 

In [32]: d.strftime('%x') 
Out[32]: '2012-05-11' 

In [33]: d.strftime('%d %b %Y') 
Out[33]: '11 Maj 2012'