gpt4 book ai didi

python - 将包含罗马数字的字符串转换为等效的整数

转载 作者:太空宇宙 更新时间:2023-11-03 13:04:02 25 4
gpt4 key购买 nike

我有以下字符串:

str = "MMX Lions Television Inc"

我需要将它转换成:

conv_str = "2010 Lions Television Inc"

我有以下函数可以将罗马数字转换成它的等价整数:

numeral_map = zip(
(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1),
('M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I')
)

def roman_to_int(n):
n = unicode(n).upper()

i = result = 0
for integer, numeral in numeral_map:
while n[i:i + len(numeral)] == numeral:
result += integer
i += len(numeral)
return result

我如何使用 re.sub 在这里获取正确的字符串?

(注意:我尝试使用此处描述的 regex:How do you match only valid roman numerals with a regular expression? 但它不起作用。)

最佳答案

始终尝试 Python Package Index在寻找通用功能/库时。

这是 list of modules related to the keyword 'roman' .

例如'romanclass'有一个实现转换的类,引用文档:

So a programmer can say:

>>> import romanclass as roman

>>> two = roman.Roman(2)

>>> five = roman.Roman('V')

>>> print (two+five)

and the computer will print:

VII

关于python - 将包含罗马数字的字符串转换为等效的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10093618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com