去掉小括号中的内容?

依依雨柔
  • 233

clipboard.png

想把每一行中 () 中的带单词的项去掉,例如第一行中红色方框中的内容都要全部去掉,其他行也是一样。
怎么写代码实现?

( (S (CC But) (NP (NP (JJ other) (NNS sources)) (ADJP (RB close) (PP (TO to) (NP (DT the) (NN sale))))) (VP (VP (VBD said) (SBAR (S (NP (NNP Vivendi)) (VP (VBD was) (VP (VBG keeping) (S (NP (DT the) (NN door)) (ADJP (JJ open) (PP (TO to) (NP (JJ further) (NNS bids)))))))))) (CC and) (VP (VBD hoped) (S (VP (TO to) (VP (VB see) (S (NP (NNS bidders)) (ADJP (JJ interested) (PP (IN in) (NP (NP (JJ individual) (NNS assets)) (ADJP (NN team) (NN up.)))))))))))) )
( (S (CC But) (NP (NP (JJ other) (NNS sources)) (ADJP (RB close) (PP (TO to) (NP (DT the) (NN sale))))) (VP (VBD said) (SBAR (S (NP (NNP Vivendi)) (VP (VBD was) (VP (VBG keeping) (S (NP (DT the) (NN door)) (VP (VP (VB open) (PP (IN for) (NP (JJ further) (NNS bids))) (PP (IN in) (NP (DT the) (JJ next) (NN day)))) (CC or) (VP (VB two.)))))))))) )
回复
阅读 2.7k
1 个回答
dokelung
  • 4.9k
✓ 已被采纳

測資:

string = '( (S (CC But) (NP (NP (JJ other) (NNS sources)) (ADJP (RB close) (PP (TO to) (NP (DT the) (NN sale))))) (VP (VBD said) (SBAR (S (NP (NNP Vivendi)) (VP (VBD was) (VP (VBG keeping) (S (NP (DT the) (NN door)) (VP (VP (VB open) (PP (IN for) (NP (JJ further) (NNS bids))) (PP (IN in) (NP (DT the) (JJ next) (NN day)))) (CC or) (VP (VB two.)))))))))) )'

代碼:

import re

result = re.sub('\(\w+ \w+\)', '',string)
print(result)

結果:

'( (S  (NP (NP  ) (ADJP  (PP  (NP  )))) (VP  (SBAR (S (NP ) (VP  (VP  (S (NP  ) (VP (VP  (PP  (NP  )) (PP  (NP   )))  (VP (VB two.)))))))))) )'

我回答過的問題: Python-QA

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏