我正在尝试从字符串中提取单词形式的数字。例如,输入字符串可能类似于:
"What is 3 million 6 hundred 5 divided by 5 hundred?"
根据这个输入,我想弄清楚如何将这两个数字分组。
["3 million 6 hundred 5", "5 hundred"]
注意:在其他输入字符串中可能会找到更多数字。
我相信正则表达式是解决这个问题的正确途径。理想情况下,我可以传入一个比例列表,例如:
["hundred", "thousand", "million", "billion", ...]
到目前为止,这就是我所拥有的:
scales= ["hundred", "thousand", "million", "billion"]
scale_pattern = '|'.join(scales)
regex = re.compile('\b(d+' + scale_pattern + 'd+)+\b')
我知道我的模式不太正确,我想要的伪代码是:
for any number of the following occurrences:
find the pattern [int word_from_list optional_int]
最佳答案
Ideally I could pass in a list of the scales
您可以像这样将它们传递到非捕获组或捕获组中。
正则表达式: (?:\d+\s(?:百万|百|千|十亿)*\s*)+
上面是一个简单的正则表达式,检查数字 \d+
后跟空格 \s
和 scale,这是可选的(通过使用 *
量词)表示最后一个数字,后跟可选的空格。整个模式重复一次或多次(通过使用+
量词)。
<强> Regex101 Demo
关于python - 正则表达式查找单词形式的大数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43156895/