【问题标题】:Special string padding characters ignored by regex's正则表达式忽略的特殊字符串填充字符
【发布时间】:2015-06-25 17:08:00
【问题描述】:

我正在解析文本,其中涉及过滤掉特殊字符或空格间隙,以便正确分类字符串。问题是原始字符串的索引映射回其他元数据(图像中 OCRd 文本的 x,y 坐标)。一旦关键字被正确分类,我想通过索引(开始和结束)映射回原始的预处理字符串,而不是关键字本身。位置比关键字更重要,因为关键字不一定是唯一的。

很多代码是这样的:

filtered_text = re.sub(\s{5,}, '', line) mobj = re.match(my_pat, filtered_text) return (mobj.start(0), mobj.end(0))

我想知道是否可以用特殊的“填充/填充”字符替换而不是替换为空字符串?这个特殊字符将满足两个要求:

(1) 它占用空间使得:

len(line) == len(filtered_line)

(2) 它被下游模式正则表达式匹配忽略。

是否有我可以使用的特殊 unicode 字符,或者可以将 re 模块中的某些内容设置为忽略特定字符?

另外,我无法将替换模式与匹配模式合并,因为代码的不同部分是相互抽象的。上面的例子很简单——实际的两个独立部分的代码很复杂。

【问题讨论】:

  • 您可以使用\0,它可能不会出现在任何地方。这是什么格式?
  • 这是 utf-8。这就是我正在尝试的:t = 'this is a\0string' mobj=re.search('(.*astring)', t) 我已经尝试了很多排列,但搜索仍然失败。有什么想法吗?
  • 我的意思是您要解析的格式的名称。它是由 Tesseracts 生成的吗?

标签: python regex unicode nlp text-processing


【解决方案1】:

当您替换空白时,您需要保留从转换位置到原始位置的映射。

def sub_with_mapping(pattern, repl, string):
    mapping = dict()
    source_index = [0]
    target_index = [0]
    target = []
    #
    def append_segment(original_len, text, keep_positions):
        for i in range(0, len(text)):
            mapping[target_index[0] + i] = source_index[0] + (i if keep_positions else 0)
        target.append(text)
        target_index[0] += len(text)
        source_index[0] += original_len
    #
    for match in re.finditer(pattern, string):
        # Append text between previous and this match
        prefix = string[source_index[0]:match.start()]
        append_segment(len(prefix), prefix, True)
        # Append replacement text
        replacement = repl
        if callable(replacement):
            replacement = replacement(match)
        append_segment(len(match.group(0)), replacement, False)
    # Append text after last match
    suffix = string[source_index[0]:]
    append_segment(len(suffix), suffix, True)
    return ''.join(target), mapping
>>> sub_with_mapping(r'\w+', 'x', 'foo --- bar --- baz')
('x --- x --- x', {0: 0, 1: 3, 2: 4, 3: 5, 4: 6, 5: 7, 6: 8, 7: 11, 8: 12, 9: 13, 10: 14, 11: 15, 12: 16})

然后您可以对返回的字符串进行匹配,并将索引映射回原始字符串。

请注意,如果您的替换长度超过一个字符,您将有多个索引映射回相同的原始索引。

如果您的字符串很长(>1 MB?),您可能需要优化数据结构。也许你可以使用范围?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-04
    • 1970-01-01
    • 2018-05-14
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    相关资源
    最近更新 更多