替换Python中的nonASCII字符:例如,“vs.”

2024-10-02 12:36:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我不想把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

这就是我所尝试的:

^{pr2}$

这很好,但是当我把它写进我的剧本里时:

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)

我有点没主意了。在


Tags: lambdainimportcleanyoustringfilterprint
3条回答

您需要decode字符串

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

这个print

^{pr2}$

这是意料之中的

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

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

可以使用replace()将撇号替换为空格,如下所示:

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

打印you ll

相关问题 更多 >

    热门问题