在空白处分割字符串,但不删除空白
我想根据空格和标点符号来分割字符串,但空格和标点符号也要保留在结果里。
举个例子:
Input: text = "This is a text; this is another text.,."
Output: ['This', ' ', 'is', ' ', 'a', ' ', 'text', '; ', 'this', ' ', 'is', ' ', 'another', ' ', 'text', '.,.']
这是我现在的做法:
def classify(b):
"""
Classify a character.
"""
separators = string.whitespace + string.punctuation
if (b in separators):
return "separator"
else:
return "letter"
def tokenize(text):
"""
Split strings to words, but do not remove white space.
The input must be of type str, not bytes
"""
if (len(text) == 0):
return []
current_word = "" + text[0]
previous_mode = classify(text)
offset = 1
results = []
while offset < len(text):
current_mode = classify(text[offset])
if current_mode == previous_mode:
current_word += text[offset]
else:
results.append(current_word)
current_word = text[offset]
previous_mode = current_mode
offset += 1
results.append(current_word)
return results
这样做是有效的,但感觉太像C语言的写法了。在Python里有没有更好的方法?
相关文章:
- 暂无相关问题
1 个回答
5
你可以使用正则表达式:
import re
re.split('([\s.,;()]+)', text)
这个表达式可以根据任意宽度的空白字符(包括制表符和换行符)以及一些标点符号来进行分割。而通过将分割后的文本分组,你可以告诉 re.sub()
把这些分组的内容也包含在输出中:
>>> import re
>>> text = "This is a text; this is another text.,."
>>> re.split('([\s.,;()]+)', text)
['This', ' ', 'is', ' ', 'a', ' ', 'text', '; ', 'this', ' ', 'is', ' ', 'another', ' ', 'text', '.,.', '']
如果你只想匹配空格(而不包括其他空白字符),可以把 \s
替换成一个空格:
>>> re.split('([ .,;()]+)', text)
['This', ' ', 'is', ' ', 'a', ' ', 'text', '; ', 'this', ' ', 'is', ' ', 'another', ' ', 'text', '.,.', '']
注意到多出来的空字符串;分割操作总是会有一个开头和一个结尾,所以如果文本是以分割组开始或结束的,结果中总会多出一个空字符串在开头或结尾。这部分是很容易去掉的。