我有一个文本文件,例如 -
{[a] abc (b(c)d)}
我想删除这些括号之间的内容[] and (())
。所以输出应该是 -
abc
我删除了括号之间的内容,但无法删除这之间的内容[]
我试过下面的代码 -
import re
with open('data.txt') as f:
input = f.read()
line = input.replace("{","")
line = line.replace("}","")
output = re.sub(r'\(.*\)', "", line)
print output
输出是 -
[a] abc
首先在我的代码中我替换{}
然后从中删除内容()
。我想添加\[.*\]
in output = re.sub(r'\(.*\)', "", line)
这条线。但找不到办法做到这一点。我还在学习Python。所以我面临这个问题。请帮忙。
我认为并不像乍看起来那么容易,您很可能需要一些平衡(递归)方法,这可以通过newer regex module:
import regex as re
string = "some lorem ipsum {[a] abc (b(c)d)} some other lorem ipsum {defg}"
rx_part = re.compile(r'{(.*?)}')
rx_nested_parentheses = re.compile(r'\((?:[^()]*|(?R))*\)')
rx_nested_brackets = re.compile(r'\[(?:[^\[\]]*|(?R))*\]')
for match in rx_part.finditer(string):
part = rx_nested_brackets.sub('',
rx_nested_parentheses.sub('',
match.group(1))).strip()
print(part)
这会产生
abc
defg
The pattern is
\( # opening parenthesis
(?: # non.capturing group
[^()]* # not ( nor )
| # or
(?R) # repeat the pattern
)*
\)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)