替换Python中的非ASCII字符:例如,'vs'

时间:2015-03-31 15:52:02

标签: python python-2.7 unicode

我不会you’ll缩减为you ll(不是youll)。这就是我正在做的事情:

>>> clean = "you'll"
>>> import string
>>> clean = filter(lambda x: x in string.printable, clean)
>>> print clean
you'll

>>> clean = "you’ll" 
>>> clean = filter(lambda x: x in string.printable, clean)
>>> print clean
youll

这就是我的尝试:

>>> clean = "you'll"
>>> clean =clean.replace('\'',' ')
>>> print clean
you ll
>>> clean = "you’ll"
>>> clean =clean.replace('’',' ')
>>> print clean
you ll

这很好用,但当我把它放在我的脚本中时:

SyntaxError: Non-ASCII character '\xe2' in file sc.py on line 177, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

所以,我添加到我的脚本的顶部:

# -*- coding: utf-8 -*- 

但是得到

clean =clean.replace('’',' ')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)

我有点想法。

3 个答案:

答案 0 :(得分:2)

这可能不是最佳答案,但一个简单的解决方案就是处理异常:

clean2 = ""
for ch in clean:
    try:
        clean2 += " " if ch == "'" else clean2 += ch
    except UnicodeDecodeError:
        clean2 += 'vs.'

答案 1 :(得分:2)

您需要decode字符串

# -*- coding: utf-8 -*- 
clean = "you’ll".decode('utf-8')
clean = clean.replace('’'.decode('utf-8'),' ')
print clean

print s

you ll

这是预期的

答案 2 :(得分:0)

您可以使用replace()替换撇号,如下所示:

print "you'll".replace("'", " ")

打印you ll