文章目錄
最近一个项目需要用脚本生成汉字拼音时来排序,组里同事说以前有同事写过一个,于是拿过来用,看了一下代码,发现有些地方还是可以优化的,
如以下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 self.polyphone = {} for line in open(polyphone_path): k, context, pron, other = line.split(' ' , 3 ) item = collections.defaultdict(dict) key = "%X" % ord(unicode(k, 'utf8' )) item[key]['context' ] = unicode(context, 'utf8' ) item[key]['pron' ] = pron if self.polyphone.has_key(key): self.polyphone[key].append(item) else : self.polyphone[key] = [] self.polyphone[key].append(item) ``` 这一段代码里需要判断字典里有没有包含key,如果没有,则要先声明value为空的list,之后再添加值,这种情况下collections中的defaultdict就派上用场了。 ``` python self.polyphone = defaultdict(list) for line in open(polyphone_path): k, context, pron, other = line.split(' ' , 3 ) item = defaultdict(dict) key = "%X" % ord(unicode(k, 'utf8' )) item[key]['context' ] = unicode(context, 'utf8' ) item[key]['pron' ] = pron self.polyphone[key].append(item) ``` defaultdict可以给定一个默认值,这样省去了判断key是否已经在字典里存在。 还见到如下代码: ``` python polyphone = False for item in self.polyphone[key]: if chars.find(item[key]['context' ]) != -1 : result.append(item[key]['pron' ].strip()[:-1 ].lower()) polyphone = True break if not polyphone: result.append(self.dict[key].split("," )[0 ].strip()[:-1 ].lower())
这段代码里,if not polyphonse判断里的句子只有在上面的for没有被break时才执行,也就是for循环执行时才执行,这种情况在编程中经常遇到,而python提供了for else循环语句,于是可以修改成:
1 2 3 4 5 6 for item in self.polyphone[key]: if chars.find(item[key]['context' ]) != -1 : result.append(item[key]['pron' ].strip()[:-1 ].lower()) break else : result.append(self.dict[key].split("," )[0 ].strip()[:-1 ].lower())
是不是瞬间简洁很多?所以说,语言特性还是有必要学习的,虽然算法和数据结构依然是核心,可是代码易维护,易懂也是非常重要的