Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.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
在Python2.7中查找模式,并在其后面添加新行_Python_Python 2.7 - Fatal编程技术网

在Python2.7中查找模式,并在其后面添加新行

在Python2.7中查找模式,并在其后面添加新行,python,python-2.7,Python,Python 2.7,我试图在文本文件中的模式后添加两个换行符,然后返回更正后的文件,而不删除模式。到目前为止,我只成功地替换了模式: def cleanTxt (list_path, results_path): with open (list_path,'r') as myText: data = myText.read() with open (results_path, 'w') as results_file: new = re.sub(r'

我试图在文本文件中的模式后添加两个换行符,然后返回更正后的文件,而不删除模式。到目前为止,我只成功地替换了模式:

def cleanTxt (list_path, results_path):

    with open (list_path,'r') as myText:
        data = myText.read()
        with open (results_path, 'w') as results_file:
            new = re.sub(r'\[.*?\]','\n\n', data)
            results_file.write(new)

            results_file.close()
我还尝试了其他方法,例如

for pattern in re.findall(r'\[{1,3}\:\[{1,3}\:\[{1,3}\]',myText):
但这一点毫无进展

如何在将图案保留在文本文件中的同时添加换行符


感谢您的帮助。

这是您的代码,经过一些修改后可以正常工作:

def cleanTxt (list_path, results_path):

    with open(list_path, 'r') as myText:
        data = myText.read()
        with open(results_path, 'w') as results_file:
            newArr = re.split(r'\[.*?\]', data)
            patt = re.findall(r'\[.*?\]', data)
            new = ""
            for i in xrange(len(patt)):
                new += newArr[i]
                new += patt[i]
                new += "\n\n"
            new += newArr[-1]
            results_file.write(new)

            results_file.close()

以下是您的代码,并对其进行了一些修改:

def cleanTxt (list_path, results_path):

    with open(list_path, 'r') as myText:
        data = myText.read()
        with open(results_path, 'w') as results_file:
            newArr = re.split(r'\[.*?\]', data)
            patt = re.findall(r'\[.*?\]', data)
            new = ""
            for i in xrange(len(patt)):
                new += newArr[i]
                new += patt[i]
                new += "\n\n"
            new += newArr[-1]
            results_file.write(new)

            results_file.close()

您只需要用匹配的文本本身以及两个换行符来替换匹配项。在Python中,替换文本中的
\g
表示整个原始匹配(注意:这是不同语言的正则表达式实现之间存在分歧的一个方面)。因此,请尝试:

new = re.sub(r'\[.*?\]', r'\g<0>\n\n', data)
new=re.sub(r'\[.\]',r'\g\n\n',数据)

您只需将匹配内容替换为匹配文本本身,再加上两个换行符即可。在Python中,替换文本中的
\g
表示整个原始匹配(注意:这是不同语言的正则表达式实现之间存在分歧的一个方面)。因此,请尝试:

new = re.sub(r'\[.*?\]', r'\g<0>\n\n', data)
new=re.sub(r'\[.\]',r'\g\n\n',数据)

漂亮。完全奏效了。谢谢,我不知道整个原始匹配的匹配模式。很漂亮。完全奏效了。谢谢,我不知道整个原始匹配的匹配模式。