使用翻译替换标点符号,这3种方式有什么区别?

3

我正在尝试将字符串中的标点符号替换为空格。我搜索了答案并在我的Python 2.7中尝试了它们,它们显示不同的结果。

s1=" merry's home, see a sign 'the-shop $on sale$ **go go!'"   #sample string

print s1.translate(string.maketrans("",""), string.punctuation) #way1

print s1.translate(None,string.punctuation)                     #way2

table=string.maketrans(string.punctuation,' '*len(string.punctuation))
print s1.translate(table)                                       #way3

它的输出结果如下:

merrys home see a sign theshop on sale go go
merrys home see a sign theshop on sale go go
merry s home  see a sign  the shop  on sale    go go  

那么这些方法之间有什么区别呢?
2个回答

3

在前两个中,实际上没有功能上的区别...你要么传递一个空的翻译表(string.maketrans("","")),要么告诉python跳过翻译步骤(None)。 翻译后,你删除了所有标点符号,因为你将string.punctuat作为应该被删除的字符。如果我是赌徒,我会打赌None版本会稍微更有效率,但你可以使用 timeit来查找答案...

最后一个示例创建了一个翻译表,将所有标点符号映射到一个空格,不删除任何内容。这就是为什么最后一个示例中有大量额外的空格。


谢谢,现在我知道了区别。 - YD Han

1

translate的文档指定了str.translate(table[, deletechars])

返回一个字符串副本,其中删除了可选参数deletechars中出现的所有字符,并且剩余的字符已通过给定的翻译映射

cont

对于仅删除字符的翻译,请将table参数设置为None

print s1.translate(string.maketrans("",""), string.punctuation)

在这种情况下,您需要删除所有标点符号,并将空字符串替换为空字符串。
print s1.translate(None,string.punctuation)

在这种情况下,您只需删除所有标点符号。
table=string.maketrans(string.punctuation,' '*len(string.punctuation))
print s1.translate(table)

在这种情况下,您需要创建一个翻译表,将标点符号替换为空格,然后进行翻译。
第一种和第二种方法的区别在于性能,正如mgilson所说,None情况确实更快:
%timeit s1.translate(string.maketrans("",""), string.punctuation) #way1
The slowest run took 4.70 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 1.27 µs per loop

%timeit s1.translate(None, string.punctuation) #way1
The slowest run took 11.41 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 627 ns per loop

第三个是完全不同的translate应用程序。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接