意義:簡單實現摩斯碼的破譯和生成
代碼:
#-*- coding: UTF-8 -*- __author__ = '007' __date__ = '2016/2/2' import pprint import re chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" codes = """.- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. .---- ..--- ...-- ....- ..... -.... --... ---.. ----. -----""" dd = dict(zip(chars.lower(),codes.split())) DD = dict(zip(codes.split(),chars.lower())) #pprint.pprint(DD) def chars2morse(char): return dd.get(char.lower(),' ') def morse2chars(morse): return DD.get(morse,' ') while True: str = raw_input() x = str.split(' ') ccc = ''.join(x) if re.match('^[0-9a-zA-Z]+$',ccc): print ' '.join(chars2morse(c) for c in ccc) else: cc = str.split() print ' '.join(morse2chars(c) for c in cc)
運行結果:
知識點:
split()
意義:通過指定分割符對字符串進行切片
語法:
str.split(str="", num=string.count(str))
- 參數str:分隔符,默認為空格
- 參數num:分割次數
返回值:返回分割后的字符串列表
實例:
1 In[2]: str = "I Love Python!" 2 In[3]: str.split() 3 Out[3]: ['I', 'Love', 'Python!'] 4 In[4]: str.split(' ',1) 5 Out[4]: ['I', 'Love Python!']
lower()
意義:轉換字符串中所有大寫字符為小寫
語法:
str.lower()
返回值:返回將字符串中所有大寫字符轉換為小寫后生成的字符串
實例:
1 In[2]: str = "I Love Python!" 2 In[5]: str.lower() 3 Out[5]: 'i love python!'
zip()
意義:Python內建函數,它接受一系列可迭代的對象作為參數,將對象中對應的元素打包成一個個tuple(元組),然后返回由這些tuples組成的 list(列表)。若傳入參數的長度不等,則返回list的長度和參數中長度最短的對象相同
語法:
zip([iterable, ...])
- 參數:任意多個列表
返回值:有元祖組成的列表
實例:
1 In[6]: a = [1,2,3] 2 In[7]: b = [4,5,6] 3 In[8]: c = [7,8,9,0] 4 In[9]: zip(a,b,c) 5 Out[9]: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
利用*號操作符,可以將list unzip(解壓)
1 In[11]: d = [[1,2,3],[4,5,6],[7,8,9]] 2 In[12]: zip(*d) 3 Out[12]: [(1, 4, 7), (2, 5, 8), (3, 6, 9)] 4 In[13]: e = [(1, 4, 7), (2, 5, 8), (3, 6, 9)] 5 In[14]: zip(*e) 6 Out[14]: [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
dict()
意義:創建新字典
語法:
dict(iterable, **kwarg)
返回值:返回一個新字典
實例:
1 #鍵值對方式構造字典 2 In[17]: dict(a=1,b=2,c=3) 3 Out[17]: {'a': 1, 'b': 2, 'c': 3} 4 #映射函數方式構造字典 5 In[18]: dict(zip(['a','b','c'],[1,2,3])) 6 Out[18]: {'a': 1, 'b': 2, 'c': 3} 7 #可迭代對象方式構造字典 8 In[19]: dict([('a',1),('b',2),('c',3)]) 9 Out[19]: {'a': 1, 'b': 2, 'c': 3}
get()
意義:返回字典中指定鍵的值,如果值不在字典中返回默認值
語法:
dict.get(key, default=None)
- 參數key:字典中要查找的鍵
- default:如果指定鍵的值不存在時,返回該默認值值
返回值:字典中指定鍵的值,如果值不在字典中返回默認值None
實例:
1 In[23]: d = {'a': 1, 'b': 2, 'c': 3} 2 In[24]: d.get('a') 3 Out[24]: 1 4 In[25]: d.get('d','Not Found!') 5 Out[25]: 'Not Found!'