如何使用Python将字符串拆分为多个标点? s='a,b,cd!e、 f\ngood\t早晚' 分隔符=['、'、'、'!'、'&'、'''.\n'、'\t'] s、 拆分()
我可以用如何使用Python将字符串拆分为多个标点? s='a,b,cd!e、 f\ngood\t早晚' 分隔符=['、'、'、'!'、'&'、'''.\n'、'\t'] s、 拆分(),python,string,split,punctuation,Python,String,Split,Punctuation,我可以用,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,来拆分字符串吗\n','\t'?是否可以为string.split()指定多个分隔符?例如,如何将s拆分为 ['a','b','c','d','e','f','good','morning','night'] 您可以使用regex实现这一点,如下所示: >>> import re >>> s = 'a,b,c d!e.f\ngood\tmorning&night' >&
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,来拆分字符串吗\n','\t'
?是否可以为string.split()
指定多个分隔符?例如,如何将s
拆分为
['a','b','c','d','e','f','good','morning','night']
您可以使用regex
实现这一点,如下所示:
>>> import re
>>> s = 'a,b,c d!e.f\ngood\tmorning&night'
>>> re.split('[?.,\n\t&! ]', s)
['a', 'b', 'c', 'd', 'e', 'f', 'good', 'morning', 'night']
如果您正在寻找使用
split()
的解决方案,那么这里有一个解决方法:
>>> identifiers = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~\n\t '
>>> "".join((' ' if c in identifiers else c for c in s)).split()
['a', 'b', 'c', 'd', 'e', 'f', 'good', 'morning', 'night']
>>标识符='!“#$%&\'()*+,-./:;?@[\]^ `{124;}~\ n\t”
>>>“”.join((“”,如果标识符中是c,则为c,如果标识符中是c,则为s中的c)).split()
['a','b','c','d','e','f','good','morning','night']
在这里,我将用字符串中的空格
“
替换所有标识符,然后根据空格拆分字符串。您可以使用regex
实现这一点,如下所示:
>>> import re
>>> s = 'a,b,c d!e.f\ngood\tmorning&night'
>>> re.split('[?.,\n\t&! ]', s)
['a', 'b', 'c', 'd', 'e', 'f', 'good', 'morning', 'night']
如果您正在寻找使用
split()
的解决方案,那么这里有一个解决方法:
>>> identifiers = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~\n\t '
>>> "".join((' ' if c in identifiers else c for c in s)).split()
['a', 'b', 'c', 'd', 'e', 'f', 'good', 'morning', 'night']
>>标识符='!“#$%&\'()*+,-./:@[\\]^{{124;}~\ n\t'
>>>“”.join((“”,如果标识符中是c,则为c,如果标识符中是c,则为s中的c)).split()
['a','b','c','d','e','f','good','morning','night']
在这里,我用一个空格
“
替换字符串中的所有标识符,然后根据空格拆分字符串。我认为如果您可以使用正则表达式进行此操作,则会更好。可能重复的?我想如果你能用正则表达式来做这个会更好。可能的副本?谢谢!我以前只使用过re.findall()
,但是这个re.split()
太棒了!非常感谢。我以前只使用过re.findall()
,但是这个re.split()
太棒了!