⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 soundex3b.py

📁 Dive into python的配套源码。
💻 PY
字号:
"""Soundex algorithmThis program is part of "Dive Into Python", a free Python book forexperienced programmers.  Visit http://diveintopython.org/ for thelatest version."""__author__ = "Mark Pilgrim (mark@diveintopython.org)"__version__ = "$Revision: 1.4 $"__date__ = "$Date: 2004/05/11 19:11:21 $"__copyright__ = "Copyright (c) 2004 Mark Pilgrim"__license__ = "Python"import string, reallChar = string.uppercase + string.lowercasecharToSoundex = string.maketrans(allChar, "91239129922455912623919292" * 2)def soundex(source):    "convert string to Soundex equivalent"    # Soundex requirements:    # source string must be at least 1 character    # and must consist entirely of letters    if (not source) or (not source.isalpha()):        return "0000"    # Soundex algorithm:    # 1. make first character uppercase    # 2. translate all other characters to Soundex digits    digits = source[0].upper() + source[1:].translate(charToSoundex)    # 3. remove consecutive duplicates    digits2 = "".join([digits[i] for i in range(len(digits))                       if i == 0 or digits[i-1] != digits[i]])            # 4. remove all "9"s    digits3 = re.sub('9', '', digits2)        # 5. pad end with "0"s to 4 characters    while len(digits3) < 4:        digits3 += "0"            # 6. return first 4 characters    return digits3[:4]if __name__ == '__main__':    from timeit import Timer    names = ('Woo', 'Pilgrim', 'Flingjingwaller')    for name in names:        statement = "soundex('%s')" % name        t = Timer(statement, "from __main__ import soundex")        print name.ljust(15), soundex(name), min(t.repeat())

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -