首页 > 解决方案 > 除撇号外,python 在所有空格和标点符号处重新拆分

问题描述

我想用除撇号之外的所有空格和标点符号来分割一个字符串。最好还是使用单引号作为分隔符,除非它是撇号。我也想保留分隔符。示例字符串
words = """hello my name is 'joe.' what's your's"""

到目前为止,这是我的 re 模式,splitted = re.split(r"[^'-\w]",words.lower()) 我尝试在 ^ 字符后加上单引号,但它不起作用。

我想要的输出是这个。splitted = [hello,my,name,is,joe,.,what's,your's]

标签: pythonstringsplitreapostrophe

解决方案


在拆分后简单地处理您的列表可能更简单,而不首先考虑它们:

>>> words = """hello my name is 'joe.' what's your's"""
>>> split_words = re.split(r"[ ,.!?]", words.lower())  # add punctuation you want to split on
>>> split_words
['hello', 'my', 'name', 'is', "'joe.'", "what's", "your's"]
>>> [word.strip("'") for word in split_words]
['hello', 'my', 'name', 'is', 'joe.', "what's", "your's"]

推荐阅读