【问题标题】:How to correct regex with one substitution, insertion or deletion in Python如何在 Python 中通过一次替换、插入或删除来更正正则表达式
【发布时间】:2020-08-01 02:48:45
【问题描述】:

我正在尝试使用正则表达式和 1 个替换、插入或删除的错误距离来更正输入字符串。

My input string is: 1 00.00000000%]
My expected output is: 100.00000000%]

The regex I am using is: (?<![\S])[1-9]\d{0,2}(?:,\d{3})*(?:\.\d+)?%?(?!\S)

由于我正在尝试的代码,它似乎没有找到 1 00.00000000% 作为模糊匹配,而是找到 1、00 和 .00000000% 作为 3 个单独的匹配。我的做法如下:

number_format_pattern_map = {
    'us_decimal_and_comma_regex': '(?<![\S])[1-9]\d{0,2}(?:,\d{3})*(?:\.\d+)?%?(?!\S)' 
}

fuzzy_matched_substrings = []
fuzzy_match_locations = []
fuzzy_changes = []
matched_formats = []

for numbers in number_format_pattern_map:
    number_pattern_string = number_format_pattern_map[numbers]
    substitution = regex.compile('(%s){s<=1}' % number_pattern_string)
    insertion = regex.compile('(%s){i<=1}' % number_pattern_string)
    deletion = regex.compile('(%s){d<=1}' % number_pattern_string)

    substitution_matches = list(substitution.finditer(input_numbers_string))
    insertion_matches = list(insertion.finditer(input_numbers_string))
    deletion_matches = list(deletion.finditer(input_numbers_string))

    fuzzy_matches = substitution_matches
    for match in insertion_matches:
        if match not in fuzzy_matches:
            fuzzy_matches.append(match)
    for match in deletion_matches:
        if match not in fuzzy_matches:
            fuzzy_matches.append(match)

    for fuzzy_match in fuzzy_matches:
        fuzzy_match_substring = fuzzy_match.group()
        fuzzy_match_location = list(fuzzy_match.span())
        fuzzy_change = list(fuzzy_match.fuzzy_changes)

根据我上面的代码,当我打印fuzzy_match_substring 时,它应该显示所有匹配的子字符串。在这一点上,我会选择最相关的一个并进行更改(删除一个空格)。

但是,当我打印模糊匹配子字符串时,我没有得到所需的子字符串 (1 00.00000000%),而是得到以下内容:

1
1
1
 00
.00000000%
0.00000000%
1
00
.00000000%

但是,当我删除字符串末尾的方括号时,我得到了所需的子字符串。

我的问题是,我怎样才能找到以下模糊匹配 1 00.00000000% 与索引 1 处的替换或插入的相应 1 错误界限。谢谢您的帮助!

【问题讨论】:

  • 我在理解您的问题时遇到了一些麻烦。你只是想删除空白空间吗?你能发布一些其他输入/输出组合的例子吗?
  • 没错..最终我想删除空格,但正则表达式编译器无法识别使用替换、插入或删除的正确子字符串,所以我无法删除它。

标签: python regex


【解决方案1】:

如果您只想删除输入中的空白区域,使用简单的正则表达式很容易:

from re import sub

x = input("Value: ")

x = sub(r"\s", "", x)

print(x)

如果你写1 00.00000000%],它会返回100.00000000%]

解释

正则表达式\s 匹配任何空格,然后我们只需使用re.sub 将匹配项替换为空字符串。

【讨论】:

  • 很难相信它这么简单,因为涉及到某种模糊匹配:-)
  • 感谢@Telmo Trooper,但是我不能这样做的原因是因为在其他情况下我确实希望数字之间有空格
  • 多发几个例子,也许我能帮上忙。您的代码的目的是什么?
  • 目的是使用具有各种不同数字/数量的文件并更正它们,以防它们被错误地 OCR(提取的文本)。所以我的目标是在正则表达式的 1 个错误范围内找到所有匹配项,并通过删除空格或在其他情况下添加逗号或小数点等来纠正它们
  • 好吧,我们需要一些需要不同处理的字符串示例。我相信您想在 Python 中将输入转换为浮点数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-19
  • 1970-01-01
  • 2011-04-26
  • 2018-04-08
相关资源
最近更新 更多