使用正则表达式将罗马数字改为整数

2024-09-29 23:21:20 发布

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

我刚开始玩正则表达式。我已经看了Google's Python regex howto和{a2}以及其他类似的问题,如Convert a string containing a roman numeral to integer equivalent和{a4},但我仍然感到困惑。在

我的代码:

user = str(input("Input the Roman numeral: "))
characters = "I", "V" "X", "L", "C", "D", "M"
values = 1, 5, 10, 50, 100, 500, 1000

def numerals(match):
    return str(user(match.group(0)))

s = str(input("Input the Roman numeral: "))
regex = re.compile(r'\b(?=[MDCLXVI]+\b)M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?    I{0,3})\b')
print regex.sub(numerals, s)

最后两行来自第一个链接。我不完全理解regex = re.compiler...,我想知道它是否真的将用户的罗马数字转换为整数? 提前谢谢


Tags: therea2convertinputmatchgoogleregex
1条回答
网友
1楼 · 发布于 2024-09-29 23:21:20

你的代码有一些问题。首先,正则表达式查找不必要的匹配项。使用括号时,请使用非匹配表达式(?:以避免找到部分匹配。线

regex = re.compile(r'\b(?=[MDCLXVI]+\b)M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})\b')

创建一个表达式来查找文本中的罗马数字。只有当您要频繁使用这个表达式时(比如在for循环中),这才是有用的。如果要使用一次,则在使用之前不需要编译。下一行再次请求用户输入,因为函数numerals调用函数user。所以它请求相同的用户输入两次。最后,它尝试用第二个用户输入替换第一个用户输入。在

^{pr2}$

从罗马式到十进制的转换是一项复杂的任务,可能需要一种算法。我对您的代码做了一些更改,只是为了使它指向正确的方向:

import re
text = input("Input the Roman numeral: ")
matches = re.findall(r'(?=\b[MDCLXVI]+\b)M{0,4}(?:CM|CD|D?C{0,3})(?:XC|XL|L?X{0,3})(?:IX|IV|V?I{0,3})', text)
for match in matches:
    print('Match: {}'.format(match))

输出:

Input a phrase with some Roman numerals: I LIVE IN III PLACES
Match: I
Match: III

相关问题 更多 >

    热门问题