输入是一个包含单词,数字和序数的句子,例如1st
,2nd
,60th
等。
输出应该只包含单词。例如:
1st
→first
2nd
→second
60th
→sixtieth
523rd
→five hundred twenty-third
num2words
将数字转换为单词。但它不适用于1st
,2nd
,60th
等序数术语。
如何使用python将序数转换为单词?
答案 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)