我需要在保留空白的同時將字符串拆分爲單詞邊界(空格)中的數組。用正則表達式對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