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

标签 python regex

我有以下字符串:

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/

相关文章:

python - Numpy 深拷贝仍在改变原始数组

Java 正则表达式 : Require zero/even amount of backslashes without including backslashes in the match

c# - 用于在 C# 中解析 Wikicode 的正则表达式

python - pyobjc安装失败: xcode-select: error: tool 'xcodebuild' requires Xcode

python - 使用 python-ldap : getting 'desc' : 'Invalid credentials' though username and password are valid 将 python 连接到 ldap 服务器

python selenium xpath 解决方案

Python:循环/理解/映射中对象创建的时间与一次性

php - 正则表达式获取 "any_characters((number,number))"

python - 在 Python 中从文件名中提取子字符串?

python - 如何使用 Python 正则表达式来匹配 MATLAB 的函数语法?