[英]How to add a missing closing parenthesis to a string in Python?
我有多個字符串要后處理,其中很多首字母縮略詞都缺少右括號。 假設下面的字符串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)'
您可以使用
text = re.sub(r'(\([A-Z]+(?!\))\b)', r"\1)", text)
使用這種方法,您還可以擺脫之前檢查文本中是否包含)
的問題,請參閱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
對於您提供的典型示例,我認為不需要使用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'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.