Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用正则表达式将罗马数字更改为整数_Python_Regex_String Conversion_Roman Numerals - Fatal编程技术网

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

Python 使用正则表达式将罗马数字更改为整数,python,regex,string-conversion,roman-numerals,Python,Regex,String Conversion,Roman Numerals,我刚开始玩弄正则表达式。我已经看了和以及其他类似的问题,如和,但我仍然感到困惑 我的代码: 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

我刚开始玩弄正则表达式。我已经看了和以及其他类似的问题,如和,但我仍然感到困惑

我的代码:

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…
,我想知道它是否真的将用户的罗马数字转换成整数?
提前感谢

您的代码中存在一些问题。首先,正则表达式正在查找不必要的匹配项。使用括号时,请使用不匹配的表达式
(?:
),以避免找到部分匹配项。行

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循环中)时才有用。如果要使用一次,则无需在使用前进行编译。下面的一行再次请求用户输入,因为函数
numbers
调用函数
user
。因此它请求相同的用户输入两次。最后,它尝试将第一个用户输入替换为第二个用户输入

print regex.sub(numerals, s)
从罗马到小数的转换是一项复杂的任务,可能需要一个算法。我对您的代码做了一些更改,以便将其指向正确的方向:

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

我不能。IDLE的子进程由于某种原因无法连接。这并不能回答问题,他们想将罗马转换为整数。