在 Python 中标记保留分隔符的字符串 [英] tokenize a string keeping delimiters in Python
本文介绍了在 Python 中标记保留分隔符的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有任何等效于 Python 中的 str.split
也返回分隔符?
在处理一些标记后,我需要为我的输出保留空白布局.
示例:
<预><代码>>>>s="\t这是一个例子">>>打印 s.split()['this', 'is', 'an', 'example']>>>打印 what_I_want(s)['\t', 'this', ' ', 'is', ' ', 'an', ' ', 'example']谢谢!
解决方案
怎么样
导入重新splitter = re.compile(r'(\s+|\S+)')splitter.findall(s)
Is there any equivalent to str.split
in Python that also returns the delimiters?
I need to preserve the whitespace layout for my output after processing some of the tokens.
Example:
>>> s="\tthis is an example"
>>> print s.split()
['this', 'is', 'an', 'example']
>>> print what_I_want(s)
['\t', 'this', ' ', 'is', ' ', 'an', ' ', 'example']
Thanks!
解决方案
How about
import re
splitter = re.compile(r'(\s+|\S+)')
splitter.findall(s)
这篇关于在 Python 中标记保留分隔符的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文