Разбиение строки в Python с помощью регулярного выражения - PullRequest
10 голосов
/ 09 мая 2011

Мне нужно разбить строку на массив по границам слов (пробел), сохраняя при этом пробел.

Например:

'this is  a\nsentence'

станет

['this', ' ', 'is', '  ', 'a' '\n', 'sentence']

Я знаю о str.partition и re.split , но ни один из них не делает то, что я хочу, и re.partition.

Как мне с достаточной эффективностью разбивать строки на пробелах в Python?

Ответы [ 3 ]

14 голосов
/ 09 мая 2011

Попробуйте:

s = "this is  a\nsentence"
re.split(r'(\W+)', s) # Notice parentheses and a plus sign.

Результат будет:

['this', ' ', 'is', '  ', 'a', '\n', 'sentence']
4 голосов
/ 09 мая 2011

Символ пробела в re - это '\ 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)

1010 * производит *

['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
3 голосов
/ 09 мая 2011

Попробуйте это:

re.split('(\W+)','this is  a\nsentence')
...