2015-11-19 41 views
2

我想根据空格和标点符号拆分字符串,但空格和标点符号仍应位于结果中。在空白处拆分字符串,但不要删除它们

例如:

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中有更好的方法吗?

+0

@ TigerhawkT3:这个问题稍微牵扯一点,因为它分裂的不仅仅是空白。但同时它只是一种变化,我完全忘记了这个答案。 :-) –

回答

4

您可以使用正则表达式:

import re 
re.split('([\s.,;()]+)', text) 

这个分裂的任意宽度的空白(包括制表符和换行符),加上精选的标点字符,并通过分组拆分文本你告诉re.sub()包括它输出:

0:

>>> import re 
>>> text = "This is a text; this is another text.,." 
>>> re.split('([\s.,;()]+)', text) 
['This', ' ', 'is', ' ', 'a', ' ', 'text', '; ', 'this', ' ', 'is', ' ', 'another', ' ', 'text', '.,.', ''] 

如果你只是想匹配的空间(而不是其他的空白),用空格代替

注意多余的空尾字符串;一个分割总是有一个头部和一个尾部,所以在分割组中开始或结束的文本在开始或结束时总是会有一个额外的空字符串。这很容易删除。

+0

如果你用'\ w +'分割也会有同样的效果。我相信在开始的时候是空字符串。 –

+0

@AruneshSingh:是的,因为然后字符串以分割组开始。 –

+0

谢谢。正则表达式肯定是强大的,我必须学习。 – Huynh

相关问题