如何正确地使用空格作为分隔符来拆分包含特殊字符句子的字符串?使用正则表达式的拆分方法无法得到期望的结果。
示例代码:
# -*- coding: utf-8 -*-
import re
s="La felicità è tutto" # "The happiness is everything" in italian
l=re.compile("(\W)").split(s)
print " s> "+s
print " wordlist> "+str(l)
for i in l:
print " word> "+i
输出结果为:
s> La felicità è tutto
wordlist> ['La', ' ', 'felicit', '\xc3', '', '\xa0', '', ' ', '', '\xc3', '', '\xa8', '', ' ', 'tutto']
word> La
word>
word> felicit
word> Ã
word>
word> ?
word>
word>
word>
word> Ã
word>
word> ?
word>
word>
word> tutto
我希望得到如下的输出:
s> La felicità è tutto
wordlist> ['La', ' ', 'felicità', ' ', 'è', ' ', 'tutto']
word> La
word>
word> felicità
word>
word> è
word>
word> tutto
需要注意的是,s是从另一个方法返回的字符串,因此我无法强制编码方式。
s=u"La felicità è tutto"
在官方的Python Unicode和正则表达式文档中,我没有找到一个令人满意的解释。
谢谢。
Alessandro