python - 我怎样才能改进这个 number2words 脚本

标签 python

import sys

words = {
    1 : 'one',
    2 : 'two',
    3 : 'three',
    4 : 'four',
    5 : 'five',
    6 : 'six',
    7 : 'seven',
    8 : 'eight',
    9 : 'nine',
    10 : 'ten',
    11 : 'eleven',
    12 : 'twelve',
    13 : 'thirteen',
    14 : 'fourteen',
    15 : 'fifteen',
    16 : 'sixteen',
    17 : 'seventeen',
    18 : 'eighteen',
    19 : 'nineteen'
}

tens = [
    '',
    'twenty',
    'thirty',
    'forty',
    'fifty',
    'sixty',
    'seventy',
    'eighty',
    'ninety',
]

placeholders = [
    '',
    'thousand',
    'million',
    'billion',
    'trillion',
    'quadrillion'
]

# segMag = segment magnitude (starting at 1)
def convertTrio(number):
    return ' '.join([words[int(number[0])],  'hundred',  convertDuo(number[1:3])]) # convertDuo(number[1:3])


def convertDuo(number):
    #if teens or less
    if int(number[0]) == 1:
        return words[int(number)]
    #twenty-five
    else:
        return tens[int(number[0]) - 1] + '-' + words[int(number[1])]


if __name__ == "__main__":

    string = []
    numeralSegments = []
    numeral = sys.argv[1]

    if int(numeral) < 100:
        print convertDuo(numeral)
    else:

        # split number into lists, grouped in threes
        for i in range (0, len(numeral), 3):
            numeralSegments.append(numeral[i:i+3])

        numeralSegments.reverse()

        # for every segment, convert to trio word and append thousand, million, etc depending on magnitude
        for i in range (len(numeralSegments)):
            string.append(convertTrio(numeralSegments[i]) + ' ' + placeholders[i])

        # reverse the list of strings before concatenating to commas
        string.reverse()        
        print ', '.join(string)

警告:我是个十足的 Python 新手。我知道可能有许多更有效的做事方式。我将不胜感激任何指向它们的指示。

编辑:该代码目前仅适用于位数为三的倍数的数字。对于解决该问题的优雅方法的建议,我将不胜感激。谢谢。

最佳答案

我想到了两个改进:

  • 40 拼写为“四十”,而不是“四十”
  • 你的程序需要单元测试

看看 Python doctestunittest模块。

关于python - 我怎样才能改进这个 number2words 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/289735/

相关文章:

python - 通过python在文本文件中查找变量的数量

python - 为什么我转换后的 Markdown HTML 标签以文本形式返回?

python - math.sin 不正确的结果

python:重新导入模块的成本是多少?

python - 同时运行多个循环

python - flask 在 cookie 中保存民意调查

python - 我如何轻松地确定 Python 类是否接受 with 关键字?

python - 如何删除 DataFrame 字符串中的特殊字符(例如 ",")?

python - 如何从 python 2.7 的列表中选择名称

javascript - 迁移学习 Tensorflow.js 大小/形状错误