在python中删除()和[]之间的文本

时间:2013-01-30 04:46:36

标签: python python-2.7

我有一长串文字,其中包含()[]。我正在尝试删除括号和括号之间的字符,但我无法弄清楚如何。

列表与此类似:

x = "This is a sentence. (once a day) [twice a day]"

这个列表不是我正在使用的,但非常相似,而且更短。

感谢您的帮助。

5 个答案:

答案 0 :(得分:49)

您可以使用re.sub功能。

>>> import re 
>>> x = "This is a sentence. (once a day) [twice a day]"
>>> re.sub("([\(\[]).*?([\)\]])", "\g<1>\g<2>", x)
'This is a sentence. () []'

如果要删除[]和(),可以使用以下代码:

>>> import re 
>>> x = "This is a sentence. (once a day) [twice a day]"
>>> re.sub("[\(\[].*?[\)\]]", "", x)
'This is a sentence.  '

重要提示:此代码不适用于嵌套符号

答案 1 :(得分:15)

运行此脚本,即使使用嵌套括号也可以 使用基本的逻辑测试。

def a(test_str):
    ret = ''
    skip1c = 0
    skip2c = 0
    for i in test_str:
        if i == '[':
            skip1c += 1
        elif i == '(':
            skip2c += 1
        elif i == ']' and skip1c > 0:
            skip1c -= 1
        elif i == ')'and skip2c > 0:
            skip2c -= 1
        elif skip1c == 0 and skip2c == 0:
            ret += i
    return ret

x = "ewq[a [(b] ([c))]] This is a sentence. (once a day) [twice a day]"
x = a(x)
print x
print repr(x)

只是因为你不运行它,
这是输出:

>>> 
ewq This is a sentence.  
'ewq This is a sentence.  ' 

答案 2 :(得分:12)

这适用于parens。正则表达式将“消耗”它匹配的文本,因此它不适用于嵌套的parens。

import re
regex = re.compile(".*?\((.*?)\)")
result = re.findall(regex, mystring)

或者这会找到一组parens ......只需循环找到更多

start = mystring.find( '(' )
end = mystring.find( ')' )
if start != -1 and end != -1:
  result = mystring[start+1:end]

答案 3 :(得分:9)

这是一个类似于@pradyunsg's answer的解决方案(它适用于任意嵌套括号):

def remove_text_inside_brackets(text, brackets="()[]"):
    count = [0] * (len(brackets) // 2) # count open/close brackets
    saved_chars = []
    for character in text:
        for i, b in enumerate(brackets):
            if character == b: # found bracket
                kind, is_close = divmod(i, 2)
                count[kind] += (-1)**is_close # `+1`: open, `-1`: close
                if count[kind] < 0: # unbalanced bracket
                    count[kind] = 0  # keep it
                else:  # found bracket to remove
                    break
        else: # character is not a [balanced] bracket
            if not any(count): # outside brackets
                saved_chars.append(character)
    return ''.join(saved_chars)

print(repr(remove_text_inside_brackets(
    "This is a sentence. (once a day) [twice a day]")))
# -> 'This is a sentence.  '

答案 4 :(得分:1)

您可以再次拆分、过滤和连接字符串。如果您的括号定义明确,则应使用以下代码。

import re
x = "".join(re.split("\(|\)|\[|\]", x)[::2])
相关问题