python - 预处理后字符索引的映射
问题描述
在预处理之后,我正在寻找一种在文本字符和相同文本的对应关系之间进行映射的方法。
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 并且第二个world
in的字符text_proc
成为.world
text
{
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!
}
其他聪明的方法??
解决方案
推荐阅读
- reactjs - 在 React/Material ui 路由中设置默认活动选项卡
- jackson - 如何防止杰克逊序列化/反序列化 POJO?
- node.js - 如何创建 API 密钥系统并在 Node js 和 express 中的受保护路由中使用它
- html - 我的 css 不工作,但没有错误
- c - 基本 C - 切换案例重复
- python - Pandas:基于匹配多级列条件的新列值
- vue.js - 如何从 vue 中的路由参数传入子组件内的更多数据值?
- kubernetes - 豆荚从同一持久卷中读取输入文件的正确方法?
- react-native - emailjs为什么不发送电子邮件?
- powershell - 根据“|”拆分字符串 PowerShell 中的字符