繁体   English   中英

python,正则表达式分裂和特殊字符

[英]python, regex split and special character

如何使用空格作为分隔符正确分割包含具有特殊字符的句子的字符串? 使用正则表达式分割方法我无法获得所需的结果。

示例代码:

# -*- 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"

关于Unicode和reg-ex的官方python文档,我没有找到令人满意的解释。

谢谢。

亚历山德罗

你的正则表达式应该是(\\s)而不是(\\W)这样:

l = re.compile("(\s)").split(s)

上面的代码将为您提供所需的确切输出。 但是以下行更有意义:

l = re.compile("\s").split(s)

它会拆分空白字符,并不会将所有空格作为匹配项。 你可能需要它们,所以我发布了两个答案。

尝试为正则表达式定义编码:

l=re.compile("\W", re.UNICODE).split(s)

使用unicode正则表达式将起作用,前提是你给它一个unicode字符串开始(你在提供的例子中没有)。 尝试这个:

s=u"La felicità è tutto" # "The happiness is everything" in italian
l=re.compile("(\W)",re.UNICODE).split(s)

print " s> "+s
print " wordlist> "+str(l)
for i in l:
    print " word> "+i

结果:

 s> La felicità è tutto
 wordlist> [u'La', u' ', u'felicit\xe0', u' ', u'\xe8', u' ', u'tutto']
 word> La
 word>  
 word> felicità
 word>  
 word> è
 word>  
 word> tutto

你的字符串s被创建为str类型,并且可能是utf-8编码,这与unicode不同。

我认为在这种情况下使用正则表达式是过度的。 如果您要做的唯一事情就是在空白字符上拆分字符串,我建议在字符串上使用split方法

s = 'La felicità è tutto'
words = s.split()

好吧,经过对Andrew Hare的一些进一步测试后,我看到那个字符为()[] - 等等不再被认为是分隔符,而我想将一个句子(维护所有分隔符)拆分成由整体组成的单词最终使用重音字符扩展字母数字值(即,在unicode中标记为字母数字的所有内容)。 因此,kgiannakakis的解决方案更正确,但它错过了将字符串s转换为unicode格式。

采用第一个例子的扩展:

# -*- coding: utf-8 -*-
import re
s="(La felicità è tutto)"#no explicit unicode given string (UTF8)
l=re.compile("([\W])",re.UNICODE).split(unicode(s,'utf-8'))#split on s converted to unicode from utf8

print " string> "+s
print " wordlist> "+str(l)
for i in l:
    print " word> "+i

现在的输出是:

 string> (La felicità è tutto)
 wordlist> [u'', u'(', u'La', u' ', u'felicit\xe0', u' ', u'\xe8', u' ', u'tutto', u')', u'']
 word> 
 word> (
 word> La
 word>  
 word> felicità
 word>  
 word> è
 word>  
 word> tutto
 word> )
 word> 

这正是我正在寻找的。

干杯:)

亚历山德罗

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM