2012-01-13 72 views
1

具体标点我使用Python V2.6和我有包含许多标点字符我想去掉一个字符串。现在我已经看过使用string.punctuation()函数,但不幸的是,我想删除除了满帧和破折号之外的所有标点符号。 ()\"'地带在Python 2.x的

任何建议 - 总共有一共只有5标点符号我想带出的?我希望这是最有效的方式。

感谢

+0

重复http://stackoverflow.com/questions/4371231/removing-punctuation-from-python-list-items/4371351#4371351 – 2012-01-13 22:14:32

回答

1

您可以使用str.translate(table[, deletechars])table设置为None,这将导致所有字符从deletechars从字符串被删除:

s.translate(None, r"()\"'") 

一些例子:

>>> "\"hello\" '(world)'".translate(None, r"()\"'") 
'hello world' 
>>> "a'b c\"d e(f g)h i\\j".translate(None, r"()\"'") 
'ab cd ef gh ij' 
1

使用string.translate

s = ''' abc(de)f\gh"i' ''' 
print(s.translate(None, r"()\"'")) 
# abcdefghi 

re.sub

import re 
re.sub(r"[\\()'\"]",'',s) 

string.translate似乎快一个数量级:

In [148]: %timeit (s*1000).translate(None, r"()\"'") 
10000 loops, best of 3: 112 us per loop 

In [146]: %timeit re.sub(r"[\\()'\"]",'',s*1000) 
100 loops, best of 3: 2.11 ms per loop 
+0

的没有必要做一个空白的转换表;只需使用“无”。 – 2012-01-13 22:15:40

+0

此外,您的代码格式已损坏。看起来像一个无与伦比的'“'。 – 2012-01-13 22:15:57

+0

乔希,感谢有关'翻译校正(无...)'在哪里格式不正确?我已经运行的代码,它似乎工作。 – unutbu 2012-01-13 22:21:41

1
>>> import re 
>>> r = re.compile("[\(\)\\\\'\"]") 
>>> r.sub("", "\"hello\" '(world)'\\\\\\") 
'hello world' 
+0

这不会从原来的字符串中删除反斜杠。'河sub('','a \\ b') - >'a \\ b'' – 2012-01-13 22:25:36

+0

对,这里有很多答案,但我认为编译后的正则表达式是最有效率的解决方案。并永远记住,“给一个男人一个正则表达式,他会匹配一个字符串......但通过教他如何创建它们,你已经给了他足够的绳索来吊起自己” – cha0site 2012-01-13 22:29:05

+0

@FJ:Gar,忘记了四倍的反斜杠规则...秒,我会编辑它... – cha0site 2012-01-13 22:29:51

0

您可以创建所有要被替换,并与您所选择的字符替换他们的字符的字典。

char_replace = {"'":"" , "(":"" , ")":"" , "\":"" , """:""} 

for i,j in char_replace.iteritems(): 
     string = string.replace(i,j) 
1

你可以让所有的字符列表你不想:

unwanted = ['(', ')', '\\', '"', '\''] 

然后,你可以做一个函数strip_punctuation(s)像这样:

def strip_punctuation(s): 
    for u in unwanted: 
     s = s.replace(u, '') 
    return s 
0
my_string = r'''\(""Hello ''W\orld)''' 
strip_chars = r'''()\'"''' 

使用理解:

''.join(x for x in my_string if x not in strip_chars) 

使用过滤器:

''.join(filter(lambda x: x not in strip_chars, my_string)) 

输出:

Hello World