在Python中,可以使用字符串的split()
方法按特定的标点符号分割字符串。以下是一个示例代码:
def split_by_punctuation(text):
# 定义标点符号
punctuation = [',', '.', ';', ':', '!', '?']
# 遍历标点符号列表,将每个标点符号替换为空格
for p in punctuation:
text = text.replace(p, ' ')
# 使用split()方法按空格分割字符串
words = text.split()
return words
# 测试代码
sentence = "Hello, world! How are you today?"
result = split_by_punctuation(sentence)
print(result)
输出结果:
['Hello', 'world', 'How', 'are', 'you', 'today']
在上述代码中,我们首先定义了一个包含常见标点符号的列表punctuation
。然后,我们使用字符串的replace()
方法将每个标点符号替换为空格。最后,我们使用split()
方法按空格分割字符串,得到一个包含分割后的单词的列表。
上一篇:按特定变量将多个数据框的值相加