如何向 Python 中的字符串添加缺少的右括号?

How to add a missing closing parenthesis to a string in Python?

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

我下面的代码只能通过将右括号单独添加到缺少的首字母缩略词来工作,而不是完整的 string/sentence。关于如何有效地执行此操作的任何提示,最好不需要迭代?

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

对于您提供的典型示例,我认为没有必要使用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'

您可以使用

text = re.sub(r'(\([A-Z]+(?!\))\b)', r")", 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")", text)
print(text)

这会产生

The dog walked (ABC) in the park

参见 a working demo on ideone.com