Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.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
Regex 删除括号中的空白和文本-使我的工作代码更加优雅_Regex_Python 2.7_Replace_Brackets - Fatal编程技术网

Regex 删除括号中的空白和文本-使我的工作代码更加优雅

Regex 删除括号中的空白和文本-使我的工作代码更加优雅,regex,python-2.7,replace,brackets,Regex,Python 2.7,Replace,Brackets,我编写了一个代码来删除txt文件中的所有括号、括号之间的文本以及多个空格 然而,我很少使用Python,很明显我的代码效率很低 做我想做的事最好的方法是什么 import re lines = open('test.txt', 'r+') lines = [re.sub('\s+',' ', line) for line in lines] #this is to kill 'tab' whitespaces lines = [re.sub(' +',' ', line) for line i

我编写了一个代码来删除txt文件中的所有括号、括号之间的文本以及多个空格

然而,我很少使用Python,很明显我的代码效率很低

做我想做的事最好的方法是什么

import re

lines = open('test.txt', 'r+')
lines = [re.sub('\s+',' ', line) for line in lines] #this is to kill 'tab' whitespaces
lines = [re.sub(' +',' ', line) for line in lines] #regular whitespace, if more than 1
lines = [re.sub('\(.*?\)','', line) for line in lines] #brackets and the text
with open('test2.txt', 'w') as out:
    out.writelines(lines)

如果您有足够的行来抵消编译正则表达式的成本,那么应该使用以下类似的方法

#!/usr/bin/env python

import re

if __name__ == "__main__":
    lines = {' foo      (bar)    '}
    parens_regex = re.compile(r'\(.*?\)')  # Non-greedy
    space_regex =  re.compile(r'\s+')

    for line in lines:
        print 'Before: "%s"' % line
        line_tmp = parens_regex.sub('', line)  # Before space-regex so we also collapse space around parens
        line_tmp = space_regex.sub(' ', line_tmp)
        line_tmp = line_tmp.strip()
        print 'After: "%s"' % line_tmp  # Prints: "foo"
我想这是否更优雅是个问题——可能不是。
您对正则表达式的了解已经足够多,可以使您的parens正则表达式不贪婪。

但也许未来的堆栈溢出阅读器不会。或者他们或您不知道如何编译正则表达式…

第二个re.sub是无用的,因为
\s
也匹配空格。谢谢!但事实上我认为我对正则表达式的了解还不够,呵呵。在
\(.*\
中,
*
是贪婪的-它将消耗尽可能多的输入,同时仍然满足正则表达式的其余部分。因此,如果您的输入字符串是,例如,
(foo(bar)(baz))
,则
*
将匹配
foo(bar)(baz)
。另一方面,您可以使量词非贪婪(通过在Python的末尾粘贴一个
):
*?
,这使得它尽可能少地消耗输入字符串,同时仍然满足整个正则表达式的约束。因此,
\(.*?\)
,在上面的输入下运行,将匹配
(foo(bar)
-基本上第一个
和第一个
之间的所有内容。谢谢,这非常有意义,非常有用!