我需要在保留空白的同时将字符串拆分为单词边界(空格)中的数组。用正则表达式对Python中的字符串进行分区
例如:
'this is a\nsentence'
将成为
['this', ' ', 'is', ' ', 'a' '\n', 'sentence']
我知道str.partition和re.split,但他们都没有非常做什么,我想并没有re.partition
。
我应该如何以合理的效率对Python中的空白字符串进行分区?
我需要在保留空白的同时将字符串拆分为单词边界(空格)中的数组。用正则表达式对Python中的字符串进行分区
例如:
'this is a\nsentence'
将成为
['this', ' ', 'is', ' ', 'a' '\n', 'sentence']
我知道str.partition和re.split,但他们都没有非常做什么,我想并没有re.partition
。
我应该如何以合理的效率对Python中的空白字符串进行分区?
试试这个:
s = "this is a\nsentence"
re.split(r'(\W+)', s) # Notice parentheses and a plus sign.
结果将是:
['this', ' ', 'is', ' ', 'a', '\n', 'sentence']
试试这个:在重新空白
re.split('(\W+)','this is a\nsentence')
符号是'\ S'没有“ \ W'
比较:
import re
s = "With a sign # written @ the beginning , that's a\nsentence,"\
'\nno more an instruction!,\tyou know ?? "Cases" & and surprises:'\
"that will 'lways unknown **before**, in 81% of time$"
a = re.split('(\W+)', s)
print a
print len(a)
print
b = re.split('(\s+)', s)
print b
print len(b)
产生
['With', ' ', 'a', ' ', 'sign', ' # ', 'written', ' @ ', 'the', ' ', 'beginning', ' , ', 'that', "'", 's', ' ', 'a', '\n', 'sentence', ',\n', 'no', ' ', 'more', ' ', 'an', ' ', 'instruction', '!,\t', 'you', ' ', 'know', ' ?? "', 'Cases', '" & ', 'and', ' ', 'surprises', ':', 'that', ' ', 'will', " '", 'lways', ' ', 'unknown', ' **', 'before', '**, ', 'in', ' ', '81', '% ', 'of', ' ', 'time', '$', '']
57
['With', ' ', 'a', ' ', 'sign', ' ', '#', ' ', 'written', ' ', '@', ' ', 'the', ' ', 'beginning', ' ', ',', ' ', "that's", ' ', 'a', '\n', 'sentence,', '\n', 'no', ' ', 'more', ' ', 'an', ' ', 'instruction!,', '\t', 'you', ' ', 'know', ' ', '??', ' ', '"Cases"', ' ', '&', ' ', 'and', ' ', 'surprises:that', ' ', 'will', ' ', "'lways", ' ', 'unknown', ' ', '**before**,', ' ', 'in', ' ', '81%', ' ', 'of', ' ', 'time$']
61
感谢。我应该更仔细地阅读're.split'文档。 – 2011-05-09 03:11:43