Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python:将两个数字转换为单词_Python_String_List - Fatal编程技术网

python:将两个数字转换为单词

python:将两个数字转换为单词,python,string,list,Python,String,List,我有一个程序,目前需要两个数字,并将它们转换成分数形式的单词, 例如,“frac(2,3)应该返回“三分之二”,但我需要第二个输入的帮助,将其转换为单词“三分之三”。现在类似于frac(2,3)的东西只返回“二”,但我需要它返回“三分之二” 我的节目: def frac (numer, den): top = {'1': "one", '2': "two", '3': "three", '4': "four"

我有一个程序,目前需要两个数字,并将它们转换成分数形式的单词, 例如,“frac(2,3)应该返回“三分之二”,但我需要第二个输入的帮助,将其转换为单词“三分之三”。现在类似于frac(2,3)的东西只返回“二”,但我需要它返回“三分之二”

我的节目:

def frac (numer, den):
    top = {'1': "one", '2': "two", '3': "three", '4': "four", '5': "five", '6': "six",
            '7': "seven", '8': "eight", '9': "nine", '0': "zero"}
    bottom = {'2': "half", '3': "third", '4':"Fourth",'5':"Fifth",'6':"sixth",'7':"seventh",'8':"eighth",'9':"ninth",'10':"tenth"}
    return " ".join(map(lambda x: top[x], str(numer)))



无需
加入
映射
,只需使用
格式

return '{} {}'.format(top[str(numer)], bottom[str(den)])
你可以用

def frac(numer, den):
    top = {'1': "one", '2': "two", '3': "three", '4': "four", '5': "five", '6': "six",
           '7': "seven", '8': "eight", '9': "nine", '0': "zero"}
    bottom = {'2': "half", '3': "thirds", '4': "Fourth", '5': "Fifth", '6': "sixth", '7': "seventh", '8': "eighth",
              '9': "ninth", '10': "tenth"}

    return f"{top[str(numer)]} {bottom[str(den)]}"


print(frac(2, 3))
产生

two thirds

这可能是一种替代方法,利用以下事实,即此处的值可以直接映射到索引:

def frac(numer, den):

    if numer > 10 or numer <= 1:
        raise ValueError(f'Numerator must have value between 1 and 10 inclusive, got {numer}.')
    elif  den < 2 or den > 9:
        raise ValueError(f'Denominators only supported for values between 2 and 10 inclusive. got {den}.')

    numerator_words = ('one','two','three','four','five','six','seven','eight','nine',)
    denominator_words = ('half','third','fourth','fifth','sixth','seventh','eighth','ninth','tenth',)

    return ' '.join((numerator[numer-1], denominator[den-2]))
def分数(数字、密度):
如果数值>10或数值9:
raise VALUELERROR(仅支持2到10之间(含2到10)的值的f'分母。got{den}.)
分子_单词=(‘一’、‘二’、‘三’、‘四’、‘五’、‘六’、‘七’、‘八’、‘九’、)
分母_单词=(‘半’、‘三’、‘四’、‘五’、‘六’、‘七’、‘八’、‘九’、‘十’、)
返回“”。联接((分子[numer-1],分母[den-2]))

另外,您可能想看看标准库中的。

尝试使用num2words库?或
返回f'{top[str(numer)]}{bottom[str(den)]}
@PeterWood:它确实是
numer
-就像在numerator中一样。