Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.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 - Fatal编程技术网

Python 提取分数的正则表达式

Python 提取分数的正则表达式,python,regex,Python,Regex,我正在寻找一个正则表达式来匹配给定字符串中格式[0-9]\/[1-9]{1,2}的分数 以下是一个例子: my_str = "This is a 1/2 1/4. Press 1/2/3. He drove a car for 1/2hour." # A free text def replace_fractions(text): fraction_dict = { '1/2': 'half', '1/4': 'quarter', '3/

我正在寻找一个正则表达式来匹配给定字符串中格式
[0-9]\/[1-9]{1,2}
的分数

以下是一个例子:

my_str = "This is a 1/2 1/4. Press 1/2/3. He drove a car for 1/2hour." # A free text

def replace_fractions(text):
    fraction_dict = {
        '1/2': 'half',
        '1/4': 'quarter',
        '3/4': 'three quarters',
        '2/3': 'two thirds',
    }
    _tmp = ' '.join([fraction_dict.get(w, w).strip() for w in text.split()])
    return _tmp

current_result = replace_fractions("This is a 1/2 1/4. Press 1/2/3. He drove a car for 1/2hour.")
当前结果:

“这是半个1/4。按1/2/3。他开车开了半个小时。”

预期结果:

“这是半刻钟。按1/2/3。他开车半小时。”

显然,需要使用正则表达式来处理
1/2/3
1/4.
1/2小时
等情况

但是,这个
[0-9]\/[1-9]{1,2}
匹配所有内容。处理这些案件的合适正则表达式是什么


注意:正则表达式只需处理上述情况。所有极端情况都可以忽略(或在专家评论后重新编辑)

您可以在您的方法中使用以下
return

return re.sub(r'(?<!\d)(?<!\d/)[0-9]/[0-9]{1,2}(?!/?\d)', lambda x: fraction_dict.get(x.group(), x.group()), text)

如果您希望分母范围从1开始,而不是从0开始,我可以建议不使用正则表达式的解决方案。@bhansa:yes-编辑了question@AmirHmZ当前位置知道怎么做就好了。
import re
my_str = "This is a 1/2 1/4. Press 1/2/3. He drove a car for 1/2hour." # A free text

def replace_fractions(text):
    fraction_dict = {
        '1/2': 'half',
        '1/4': 'quarter',
        '3/4': 'three quarters',
        '2/3': 'two thirds',
    }
    return re.sub(r'(?<!\d)(?<!\d/)[0-9]/[0-9]{1,2}(?!/?\d)', lambda x: fraction_dict.get(x.group(), x.group()), text)

current_result = replace_fractions("This is a 1/2 1/4. Press 1/2/3. He drove a car for 1/2hour.")
print(current_result)
# => This is a half quarter. Press 1/2/3. He drove a car for halfhour.