Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.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

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 - Fatal编程技术网

Python 如何在正则表达式中使用正则表达式变量?

Python 如何在正则表达式中使用正则表达式变量?,python,regex,Python,Regex,我使用以下模式清理一段文本(将匹配项替换为null): 但是新模式与输入文本中可以使用原始正则表达式模式进行匹配的部分不匹配。我使用的代码是: lookahead_string = '' relators = ["because", "since"] for rel in relators: lookahead_string += '(?<!\b'+rel+'\b)' text = re.sub(r'{\s{\s\"[A-Za-z0-9.,\

我使用以下模式清理一段文本(将匹配项替换为null):

但是新模式与输入文本中可以使用原始正则表达式模式进行匹配的部分不匹配。我使用的代码是:

    lookahead_string = ''
    relators = ["because", "since"]
    for rel in relators:
        lookahead_string += '(?<!\b'+rel+'\b)'
    text = re.sub(r'{\s{\s\"[A-Za-z0-9.,\-:]*'+lookahead_string+r'\"\s}\s\"[A-Za-z0-9.,\-:]*\"\s}', "", text)
    text = ' '.join(text.split())
lookahead\u string=''
relators=[“因为”,“因为”]
对于rel in继电器:

lookahead_string+='(?建议:不要弄乱复杂的字符串语法,而是将字符串转换为Python列表

import ast
l = ast.literal_eval("[" + s.replace("}", "],").replace("{", "[") + "]")
#[[[[['I'], 'PRP'], 'NP'], [[[[['did'], 'VBD'], [['not'], 'RB'], 'VP'],
#  ..., 'S'], '']

现在,您可以对数据应用简单的列表函数,完成后,将列表转换为带括号的字符串。

这是一个很好的建议,但是,在某个时候,我需要使用有关解析树中每个元素深度的信息。因此,我不太确定,如果像您提到的那样将树转换为列表,是否可以保留结构信息该列表与原始字符串完全等效。但是,原始字符串具有嵌套括号,通常无法用正则表达式解析。
{\s{\s\"[A-Za-z0-9.,\-:]*'+lookahead_string+r'\"\s}\s\"[A-Za-z0-9.,\-:]*\"\s}
    lookahead_string = ''
    relators = ["because", "since"]
    for rel in relators:
        lookahead_string += '(?<!\b'+rel+'\b)'
    text = re.sub(r'{\s{\s\"[A-Za-z0-9.,\-:]*'+lookahead_string+r'\"\s}\s\"[A-Za-z0-9.,\-:]*\"\s}', "", text)
    text = ' '.join(text.split())
import ast
l = ast.literal_eval("[" + s.replace("}", "],").replace("{", "[") + "]")
#[[[[['I'], 'PRP'], 'NP'], [[[[['did'], 'VBD'], [['not'], 'RB'], 'VP'],
#  ..., 'S'], '']