展开全部
下面的函数实现将你所说的字符串转换成一个列表e68a84e8a2ad62616964757a686964616f31333335336536,列表每个元素是符合你要求的字符串。 如果你能确保输入的字符串里的符号(括号,<>等)一定是成对匹配出现的,那么可以把源码中的 raise Exception 相关的代码删除掉。那几行都是在符号不成对的时候报错用的。
symbol_L = ['{', '(', '[', '
symbol_R = ['}', ')', ']', '>',]
def my_split(text):
retlist = []
stack = []
msg = []
for c in text:
if c == ' ' and len(stack) == 0:
if len(msg) > 0:
retlist.append(''.join(msg))
msg = []
continue
msg.append(c)
if c in symbol_L:
stack.append(c)
continue
for idx, symbol in enumerate(symbol_R):
if c != symbol:
continue
if len(stack) == 0 or stack[-1] != symbol_L[idx]:
raise Exception("Unballanced symbols")
stack.pop()
if len(stack) == 0:
retlist.append(''.join(msg))
msg = []
break
if len(stack) > 0:
raise Exception("Unballanced symbols")
return retlist
使用的方法很简单:
>>> my_split("(aaa ) {bbb} [ccc ppp] eee zzz ")
['(aaa )', '{bbb}', '[ccc ppp]', '', 'eee', 'zzz', '']
想知道哪个字符串是没有被符号括起来的也很简单,用下面的代码即可:result = my_split("(aaa ) {bbb} [ccc ppp] eee zzz ")
for i, w in enumerate(result):
if w[0] not in symbol_L:
print 'word %s at index %d is not enclosed' % (w, i)
可以看到类似于
word eee at index 4 is not enclosed
word zzz at index 5 is not enclosed
的打印。