【问题标题】:How to add a missing closing parenthesis to a string in Python?如何在 Python 中为字符串添加缺少的右括号?
【发布时间】:2021-07-27 18:08:24
【问题描述】:

我有多个字符串要后处理,其中很多首字母缩略词都缺少右括号。假设下面的字符串text,但也假设这种类型的丢失括号经常发生。

我下面的代码只能通过将右括号独立地添加到缺少的首字母缩写词中,而不是完整的字符串/句子。关于如何有效地做到这一点,最好不需要迭代的任何提示?

import re
 
#original string
text = "The dog walked (ABC in the park"

#Desired output:
desired_output = "The dog walked (ABC) in the park"


#My code: 
acronyms = re.findall(r'\([A-Z]*\)?', text)
for acronym in acronyms:
  if ')' not in acronym: #find those without a closing bracket ')'. 
    print(acronym + ')') #add the closing bracket ')'.

#current output:
>>'(ABC)'

【问题讨论】:

    标签: python regex string re


    【解决方案1】:

    对于您提供的典型示例,我认为不需要使用regex 您可以只使用一些字符串方法:

    text = "The dog walked (ABC in the park"
    withoutClosing = [word for word in text.split() if word.startswith('(') and not word.endswith(')') ]
    withoutClosing
    Out[45]: ['(ABC']
    

    现在你有了没有右括号的单词,你可以替换它们:

    for eachWord in withoutClosing:
        text = text.replace(eachWord, eachWord+')')
        
    text
    Out[46]: 'The dog walked (ABC) in the park'
    

    【讨论】:

      【解决方案2】:

      你可以使用

      text = re.sub(r'(\([A-Z]+(?!\))\b)', r"\1)", text)
      

      通过这种方法,您还可以摆脱检查文本之前是否有),请参阅a demo on regex101.com


      全文:

      import re
       
      #original string
      text = "The dog walked (ABC in the park"
      text = re.sub(r'(\([A-Z]+(?!\))\b)', r"\1)", text)
      print(text)
      

      这会产生

      The dog walked (ABC) in the park
      

      a working demo on ideone.com

      【讨论】:

      • 啊,太好了,这正是我想要的。所以r"\1)" 用右括号代替?
      猜你喜欢
      • 2021-08-22
      • 1970-01-01
      • 2015-03-31
      • 2019-04-18
      • 2018-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多