我有一个字符串需要在多个字符上进行拆分,不能使用正则表达式。例如,我需要像下面这样的内容:
>>>string="hello there[my]friend"
>>>string.split(' []')
['hello','there','my','friend']
有没有类似这样的Python代码?
我有一个字符串需要在多个字符上进行拆分,不能使用正则表达式。例如,我需要像下面这样的内容:
>>>string="hello there[my]friend"
>>>string.split(' []')
['hello','there','my','friend']
re.split
是一个好方法。>>> def multisplit(s, delims):
... pos = 0
... for i, c in enumerate(s):
... if c in delims:
... yield s[pos:i]
... pos = i + 1
... yield s[pos:]
...
>>> list(multisplit('hello there[my]friend', ' []'))
['hello', 'there', 'my', 'friend']
不使用正则表达式的解决方案:
from itertools import groupby
sep = ' []'
s = 'hello there[my]friend'
print [''.join(g) for k, g in groupby(s, sep.__contains__) if not k]
我刚刚在这里发布了一个解释 https://dev59.com/onNA5IYBdhLWcg3wL6sc#19211729
一种不使用正则表达式的递归解决方案。与其他答案相比,仅使用基本的Python。
def split_on_multiple_chars(string_to_split, set_of_chars_as_string):
# Recursive splitting
# Returns a list of strings
s = string_to_split
chars = set_of_chars_as_string
# If no more characters to split on, return input
if len(chars) == 0:
return([s])
# Split on the first of the delimiter characters
ss = s.split(chars[0])
# Recursive call without the first splitting character
bb = []
for e in ss:
aa = split_on_multiple_chars(e, chars[1:])
bb.extend(aa)
return(bb)
该函数与Python的常规string.split(...)
非常相似,但可以接受多个分隔符。
使用示例:
print(split_on_multiple_chars('my"example_string.with:funny?delimiters', '_.:;'))
输出:
['my"example', 'string', 'with', 'funny?delimiters']
如果您不担心长字符串,可以使用string.replace()强制所有分隔符相同。以下代码将字符串按-
和,
进行拆分:
x.replace('-', ',').split(',')
如果有多个分隔符,可以采用以下方法:
def split(x, delimiters):
for d in delimiters:
x = x.replace(d, delimiters[0])
return x.split(delimiters[0])
re.split
是这里的正确工具。
>>> string="hello there[my]friend"
>>> import re
>>> re.split('[] []', string)
['hello', 'there', 'my', 'friend']
[...]
定义了一个字符类。方括号内的任何字符都将匹配。我在括号之间的空格方式避免了需要转义它们,但是模式 [\[\] ]
也可以工作。>>> re.split('[\[\] ]', string)
['hello', 'there', 'my', 'friend']
re.DEBUG
标志对于re.compile也很有用,因为它会打印出模式将匹配的内容:
>>> re.compile('[] []', re.DEBUG)
in
literal 93
literal 32
literal 91
<_sre.SRE_Pattern object at 0x16b0850>
(其中32、91、93是分别赋给、
[
、]
的ASCII值)