tokenize一个字符串,保留Python中的分隔符

时间:2009-11-30 15:02:38

标签: python string split tokenize

Python中是否还有等同于str.split的返回分隔符?

我需要在处理一些令牌后保留输出的空白布局。

示例:

>>> s="\tthis is an  example"
>>> print s.split()
['this', 'is', 'an', 'example']

>>> print what_I_want(s)
['\t', 'this', ' ', 'is', ' ', 'an', '  ', 'example']

谢谢!

5 个答案:

答案 0 :(得分:19)

怎么样

import re
splitter = re.compile(r'(\s+|\S+)')
splitter.findall(s)

答案 1 :(得分:6)

>>> re.compile(r'(\s+)').split("\tthis is an  example")
['', '\t', 'this', ' ', 'is', ' ', 'an', '  ', 'example']

答案 2 :(得分:4)

re模块提供此功能:

>>> import re
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']

(引自Python文档)。

对于您的示例(在空格上拆分),请使用re.split('(\s+)', '\tThis is an example')

关键是将正则表达式括起来在捕获括号中分割。这样,分隔符就会添加到结果列表中。

编辑:正如所指出的,任何前面/后面的分隔符当然也会被添加到列表中。为避免这种情况,您可以先在输入字符串上使用.strip()方法。

答案 3 :(得分:3)

你看过pyparsing了吗?借用the pyparsing wiki

的例子
>>> from pyparsing import Word, alphas
>>> greet = Word(alphas) + "," + Word(alphas) + "!"
>>> hello1 = 'Hello, World!'
>>> hello2 = 'Greetings, Earthlings!'
>>> for hello in hello1, hello2:
...     print (u'%s \u2192 %r' % (hello, greet.parseString(hello))).encode('utf-8')
... 
Hello, World! → (['Hello', ',', 'World', '!'], {})
Greetings, Earthlings! → (['Greetings', ',', 'Earthlings', '!'], {})

答案 4 :(得分:-1)

感谢大家指点re模块,我仍然试图在它之间做出决定并使用我自己的函数返回一个序列......

def split_keep_delimiters(s, delims="\t\n\r "):
    delim_group = s[0] in delims
    start = 0
    for index, char in enumerate(s):
        if delim_group != (char in delims):
            delim_group ^= True
            yield s[start:index]
            start = index
    yield s[start:index+1]

如果我有时间,我会对他们进行基准测试xD