具体标点我使用Python V2.6和我有包含许多标点字符我想去掉一个字符串。现在我已经看过使用string.punctuation()
函数,但不幸的是,我想删除除了满帧和破折号之外的所有标点符号。 ()\"'
地带在Python 2.x的
任何建议 - 总共有一共只有5标点符号我想带出的?我希望这是最有效的方式。
感谢
具体标点我使用Python V2.6和我有包含许多标点字符我想去掉一个字符串。现在我已经看过使用string.punctuation()
函数,但不幸的是,我想删除除了满帧和破折号之外的所有标点符号。 ()\"'
地带在Python 2.x的
任何建议 - 总共有一共只有5标点符号我想带出的?我希望这是最有效的方式。
感谢
您可以使用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'
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
的没有必要做一个空白的转换表;只需使用“无”。 – 2012-01-13 22:15:40
此外,您的代码格式已损坏。看起来像一个无与伦比的'“'。 – 2012-01-13 22:15:57
乔希,感谢有关'翻译校正(无...)'在哪里格式不正确?我已经运行的代码,它似乎工作。 – unutbu 2012-01-13 22:21:41
>>> import re
>>> r = re.compile("[\(\)\\\\'\"]")
>>> r.sub("", "\"hello\" '(world)'\\\\\\")
'hello world'
您可以创建所有要被替换,并与您所选择的字符替换他们的字符的字典。
char_replace = {"'":"" , "(":"" , ")":"" , "\":"" , """:""}
for i,j in char_replace.iteritems():
string = string.replace(i,j)
你可以让所有的字符列表你不想:
unwanted = ['(', ')', '\\', '"', '\'']
然后,你可以做一个函数strip_punctuation(s)
像这样:
def strip_punctuation(s):
for u in unwanted:
s = s.replace(u, '')
return s
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
重复http://stackoverflow.com/questions/4371231/removing-punctuation-from-python-list-items/4371351#4371351 – 2012-01-13 22:14:32