首页 > 解决方案 > 预处理后字符索引的映射

问题描述

在预处理之后,我正在寻找一种在文本字符和相同文本的对应关系之间进行映射的方法。

text = "Hello https://world world"

def remove_url(text):
    text = re.sub(r'http\S+', '', text)
    text = re.sub(r'www\.\S+', '', text)
    text = re.sub(' +', ' ',text)
    return text

text_proc = remove_url(text)
print(text_proc)

有了这个输出

Hello world

现在我想要一种映射,其中键是 的索引,text_proc值是text.

该方法remove_url是通用的。在我的目的中,我还有其他类型的更复杂的预处理(如 HTML 删除等)。

我试过这样的代码:

import json

mapping={}

cur_index_text=0
for i_proc in range(len(text_proc)):
    for i in range(cur_index_text, len(text)):
        if text_proc[i_proc]==text[i]:
            mapping[i_proc] = i
            cur_index_text = i+1
            break
        mapping[i_proc] = None

但它显然不起作用,因为我正在逐个检查 char 并且第二个worldin的字符text_proc成为.worldtext

{
  0: 0, #ok
  1: 1, #ok
  2: 2, #ok
  3: 3, #ok
  4: 4, #ok
  5: 5, #ok
  6: null, #ok
  7: null, #ok
  8: 14, #no!
  9: 15, #no!
  10: 16, #no!
  11: 17, #no!
  12: 18 #no!
}

其他聪明的方法??

标签: pythonmappingcharacteroffset

解决方案


推荐阅读