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

在Python中使用正则表达式删除字符后在文本中插入标记

在Python中使用正则表达式删除字符后在文本中插入标记,python,regex,string,filtering,Python,Regex,String,Filtering,我需要标记原始源列中的文本,该列与另一列中的文本相匹配,在另一列中,人类提取了相同的信息。原始列是未筛选的,像.find()和regex maching这样的方法只有在删除某些字符或regex短语时才起作用。问题是,我无法真正跟踪我删除了多少字符,以便在原始文本中将标记放在正确的位置 我这样做是为了知道删除字符的位置: def delete_characters(text, characters): # Find positions of characters-to-delete and

我需要标记原始源列中的文本,该列与另一列中的文本相匹配,在另一列中,人类提取了相同的信息。原始列是未筛选的,像.find()和regex maching这样的方法只有在删除某些字符或regex短语时才起作用。问题是,我无法真正跟踪我删除了多少字符,以便在原始文本中将标记放在正确的位置

我这样做是为了知道删除字符的位置:

def delete_characters(text, characters):
    # Find positions of characters-to-delete and delete them (positions are needed to compute shift)
    rx = '[' + re.escape(''.join(characters)) + ']'
    deleted_positions = [m.start() for m in re.finditer(rx, text)]     
    return re.sub(rx, '', text) , deleted_positions #remove the list of chars defined above
然后,如果我在过滤后匹配了某个内容,我将标记为:(where position是找到匹配项的位置)

def插入标签(cls、文本、位置、已删除位置、待打印):
移位\u l=总和(如果i<位置[0],则删除的\u位置中的i为1)
移位\u r=总和(如果i<位置[1],则删除位置中的i为1)
begin_tag=f“[{cls.tag_name}”
end_tag=f“[/{cls.tag_name}”
开始位置=位置[0]+移位位置
结束位置=位置[1]+移位位置
text=文本[:开始位置]+开始位置标记+文本[开始位置:结束位置]+结束位置标记+文本[结束位置:]
返回文本,str(开始位置)
这似乎适用于单个字符,但如果我想过滤类似regex的标记,则标记最终会出现在错误的位置。

您可以使用
re.sub()
将查询字符串中的空格替换为
[\W\u]+

重新导入
text=“”这是文本1。这是
文本2。这是文本3
query\u string=“这是文本3”
打印(re.sub(“+query\u string.replace”(“,“[\W\u]+”+”+“[\W\u]+)”,r“[tag]\1[/tag]”,text))
输出

This is text 1. This is
 text, 2. [tag]This is ,text_3 .[/tag]
您可以使用
re.sub()
,方法是将查询字符串中的空格替换为
[\W\]+

重新导入
text=“”这是文本1。这是
文本2。这是文本3
query\u string=“这是文本3”
打印(re.sub(“+query\u string.replace”(“,“[\W\u]+”+”+“[\W\u]+)”,r“[tag]\1[/tag]”,text))
输出

This is text 1. This is
 text, 2. [tag]This is ,text_3 .[/tag]

如果我的原始列是:“这是文本1。这是\r\n文本,2。这是文本3。”而我的查询列是“这是文本3”,我需要用“这是文本1。这是\r\n文本,2。[tag]这是,文本3.[/tag]”结束如果我的原始列是:“这是文本1。这是\r\n文本,2。这是文本3。”而我的查询列是“这是文本3”,我需要用“这是文本1。这是\r\n文本,2。[tag]这是,文本3.[/tag]”结束