Python中的单词的序数

时间:2017-10-30 12:21:16

标签: python

问题

输入是一个包含单词,数字和序数的句子,例如1st2nd60th等。

输出应该只包含单词。例如:

  • 1stfirst
  • 2ndsecond
  • 60thsixtieth
  • 523rdfive hundred twenty-third

我尝试了什么

num2words将数字转换为单词。但它不适用于1st2nd60th等序数术语。

问题

如何使用python将序数转换为单词?

4 个答案:

答案 0 :(得分:6)

使用num2words,您应该使用ordinal=True来获得所需的输出,如documentation中所述:

from num2words import num2words

print(num2words(1, ordinal=True))
print(num2words(2, ordinal=True))
print(num2words(60, ordinal=True))
print(num2words(523, ordinal=True))

打印:

first
second
sixtieth
five hundred and twenty-third

答案 1 :(得分:3)

从字符串中删除序数结尾:

import re

re.findall('\d+', stringValue)

然后使用

num2words(foundInteger, ordinal=True)

答案 2 :(得分:3)

整个解决方案

import re
from num2words import num2words


def replace_ordinal_numbers(text):
    re_results = re.findall('(\d+(st|nd|rd|th))', text)
    for enitre_result, suffix in re_results:
        num = int(enitre_result[:-2])
        text = text.replace(enitre_result, num2words(num, ordinal=True))
    return text


def replace_numbers(text):
    re_results = re.findall('\d+', text)
    for term in re_results:
        num = int(term)
        text = text.replace(term, num2words(num))
    return text


def convert_numbers(text):
    text = replace_ordinal_numbers(text)
    text = replace_numbers(text)

    return text


if __name__ == '__main__':
    assert convert_numbers('523rd') == 'five hundred and twenty-third'

答案 3 :(得分:0)

对于从1到12的序数的数字,不确定如何“更短”地进行,但是这种方式使用了基本的python函数:)

def integerToOrdinal(x):
if x == 1
 ordinal = "first"
if x == 2:
    ordinal = "second"
if x == 3:
    ordinal = "third"
if x == 4:
    ordinal = "fourth"
if x == 5: 
    ordinal = "fifth"
if x == 6: 
    ordinal = "sixth"
if x == 7: 
    ordinal = "seventh"
if x == 8: 
    ordinal = "eigth"
if x == 9: 
    ordinal = "ninth"
if x == 10: 
    ordinal = "tenth"
if x == 11: 
    ordinal = "eleventh"
if x == 12: 
    ordinal = "twelfth"
return ordinal

x = int(input())
result = integerToOrdinal(x)
print(result)