python - 仅删除嵌套括号中的括号
问题描述
我有一组格式无效的解析树,其中的单词用括号括起来。
string = (NP (NN (Police)) (SBAR (SC (for)) (S (NP-SBJ (*)) (VP (VB (secure)) (NP (NN (olympic games)))))))
我试图删除括号内没有单词,结果我删除了所有括号。
re.sub(r'[\(\)]','',string)
这也不起作用。
re.sub(r'\s\(.*\)\))
因为我认为基于第二个闭括号的模式就像
(Police)) (for)) (*)) (secure)) (olympic games))
我想删除单词两侧的括号,而没有像这样删除单词。有什么帮助吗?
result = (NP (NN Police) (SBAR (SC for) (S (NP-SBJ *) (VP (VB secure) (NP (NN olympic games))))))
解决方案
您可以使用
re.sub(r'\(([^()]*)\)', r'\1', s)
请参阅正则表达式演示。
细节
\(
- 一个(
字符([^()]*)
- 第 1 组(\1
指替换模式中的该组值):0 或更多字符而不是括号\)
-
请参阅Python 演示:
import re
s = "(NP (NN (Police)) (SBAR (SC (for)) (S (NP-SBJ (*)) (VP (VB (secure)) (NP (NN (olympic games)))))))"
print(re.sub(r'\(([^()]*)\)', r'\1', s))
# => (NP (NN Police) (SBAR (SC for) (S (NP-SBJ *) (VP (VB secure) (NP (NN olympic games))))))