python - 在空格处拆分字符串,但不要删除它们

标签 python string

<分区>

我想根据空格和标点符号拆分字符串,但空格和标点符号应该仍然在结果中。

例如:

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

最佳答案

您可以使用正则表达式:

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', '.,.', '']

注意额外的尾随空字符串;拆分总是有头和尾,因此在拆分组中开始或结束的文本总是在开头或结尾有一个额外的空字符串。这很容易删除。

关于python - 在空格处拆分字符串,但不要删除它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33803306/

相关文章:

swift - 使用 Swift 删除字符串中的一行字符

c++ - For 循环未按预期执行

ios - 无法使用类型为 'String' 的索引下标类型为 'String' 的值

c# - ToString 方法并返回静态字符串

python - 将图像插入 pdf 文件

python - 类型错误 Django

python - 如何被动嗅探 TCP/HTTP get 请求

计算字符串中 101 的个数

python - pd.cut 的令人困惑的结果

python - python 上有两个变量的线性回归