Python中的序数到单词

2024-04-26 00:43:16 发布

您现在位置:Python中文网/ 问答频道 /正文

问题

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

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

  • 1st→{}
  • 2nd→{}
  • 60th→{}
  • 523rd→{}

我试过的

num2words将数字转换为单词。但它不适用于顺序项,如1st2nd60th

问题

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


Tags: 顺序数字单词句子序数num2words
3条回答

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

import re

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

然后使用

^{pr2}$

使用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))

印刷品:

^{pr2}$

整个解决方案

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'

相关问题 更多 >