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

时间:2015-11-19 11:58:13

标签: python string

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

例如:

<inSequence>
  <script language="js">mc.setPayloadXML(new XML(mc.getPayloadXML()..*::xml.toXMLString()));</script>
  <property xmlns:ns="http://ProxyService"
            name="phoneValue"
            expression="//ns:xml/ns:phone"
            scope="default"
            type="STRING"/>
  <log level="custom">
    <property name="logValue" expression="get-property('phoneValue')"/>
  </log>
  <xslt key="in_xslt">
    <property name="phone" expression="get-property('phoneValue')"/>
  </xslt>
  <log level="full"/>
  <send>
    <endpoint>
      <address uri="http://localhost:322/"/>
    </endpoint>
  </send>
</inSequence>

以下是我目前正在做的事情:

Input: text = "This is a text; this is another   text.,."
Output: ['This', ' ', 'is', ' ', 'a', ' ', 'text', '; ', 'this', ' ', 'is', ' ', 'another', '   ', 'text', '.,.']

它有效,但它是C风格。在Python中有更好的方法吗?

1 个答案:

答案 0 :(得分:4)

您可以使用正则表达式:

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

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

相关问题