我有几个字符串,当它们不在括号内时,我想用空格分隔它们。
例如
sentence = "blah (blah2 (blah3))|blah4 blah5"
Run Code Online (Sandbox Code Playgroud)
应该产生
["blah", "(blah2 (blah3))|blah4", "blah5"]
Run Code Online (Sandbox Code Playgroud)
我试过了:
re.split(r"\s+(?=[^()]*(?:\(|$))", sentence)
Run Code Online (Sandbox Code Playgroud)
但它会产生:
['blah', '(blah2', '(blah3))|blah4', 'blah5']
Run Code Online (Sandbox Code Playgroud)
正如评论中所说,由于括号嵌套,不可能使用正则表达式来处理它。
另一种选择是一些很好的旧字符串处理,在括号上嵌套计数:
def parenthesis_split(sentence,separator=" ",lparen="(",rparen=")"):
nb_brackets=0
sentence = sentence.strip(separator) # get rid of leading/trailing seps
l=[0]
for i,c in enumerate(sentence):
if c==lparen:
nb_brackets+=1
elif c==rparen:
nb_brackets-=1
elif c==separator and nb_brackets==0:
l.append(i)
# handle malformed string
if nb_brackets<0:
raise Exception("Syntax error")
l.append(len(sentence))
# handle missing closing parentheses
if nb_brackets>0:
raise Exception("Syntax error")
return([sentence[i:j].strip(separator) for i,j in zip(l,l[1:])])
print(parenthesis_split("blah (blah2 (blah3))|blah4 blah5"))
Run Code Online (Sandbox Code Playgroud)
结果:
['blah', '(blah2 (blah3))|blah4', 'blah5']
Run Code Online (Sandbox Code Playgroud)
l包含出现非括号保护空间的字符串的索引。最后,通过对列表进行切片来生成数组。
请注意strip()最后处理多个分隔符的出现,并在开始时删除前导/尾随分隔符,这将在返回的列表中创建空项目。
| 归档时间: |
|
| 查看次数: |
3620 次 |
| 最近记录: |