2013-05-26 150 views
1

我有一串非ASCII字符的字符串,我想刪除它。我在Python 3使用了以下功能:刪除包含ASCII字符串

def removeNonAscii(s): 
    return "".join(filter(lambda x: ord(x)<128, s)) 

str1 = "Hi there!\xc2\xa0My\xc2\xa0name\xc2\xa0is\xc2\xa0Blue " 
new = removeNonAscii(str1) 

新的字符串變成:

您好MynameisBlue

是否有可能字符串,使得它之間得到空間:

你好!我的名字是藍色的

+0

['DEF removeNonAscii(S):返回 「」。加入(過濾器(拉姆達X:ORD(X)<128,S) )'](http://stackoverflow.com/questions/1342000/how-to-replace-non-ascii-characters-in-string)和[這裏](http://stackoverflow.com/questions/8689795/python -remove-non-ascii-characters-but-leave-period-and-spaces)是一個更有幫助的問答問與答 –

+0

@GrijeshChauhan:它與OP有相同的一段代碼! – nhahtdh

+0

@GrijeshChauhan這是我用過的,但我仍然有與上面提到的 – lost9123193

回答

3

下面的代碼等同於您當前的代碼,除了對於US-ASCII範圍之外的連續字符序列,它將用一個空格替換整個序列(ASCII 32) 。

import re 
re.sub(r'[^\x00-\x7f]+', " ", inputString) 

請注意,上面的代碼允許控制字符,也是問題中的代碼。

+0

)發表了評論:正是我想要的!非常感謝! – lost9123193

0

正則表達式獲得在這裏,但FWIW這裏是一個itertools.groupby溶液:

from itertools import groupby 
text = "Hi there!\xc2\xa0My\xc2\xa0name\xc2\xa0is\xc2\xa0Blue " 
def valid(c): 
    return ord(c) < 128 

def removeNonAscii(s): 
    return ''.join(''.join(g) if k else ' ' for k, g in groupby(s, valid)) 

>>> removeNonAscii(text) 
'Hi there! My name is Blue '