仅移除嵌套括号中的括号

3

我有一组解析树,其中的格式无效,其中的单词用括号括起来。

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'\(([^()\s]*)\)', r'\1', s),参见 https://ideone.com/pD0I9j - Wiktor Stribiżew
成功了!谢谢!@WiktorStribiżew - Yarp
1个回答

3

您可以使用

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))))))

应该使用 re.sub(r'(([^()]*))', r'\1', s) 来得到期望的答案。 - Dave
@Dave OP确认 re.sub(r'\(([^()\s]*)\)', r'\1', s) 的效果符合预期。如果删除\s,类似(abc def)的子字符串也会被删除。 - Wiktor Stribiżew
你的答案输出与原始问题所需的输出不匹配,请查看“奥林匹克运动会”。 - Dave
@Dave 嗯,那我就不明白 OP 的意思了 :) 我已经编辑了回答。 - Wiktor Stribiżew

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接