首页 > 后端开发 > Python教程 > 在 Python 中从字符串中删除标点符号的最有效方法是什么?

在 Python 中从字符串中删除标点符号的最有效方法是什么?

DDD
发布: 2024-12-22 01:30:22
原创
298 人浏览过

What's the Most Efficient Way to Remove Punctuation from a String in Python?

从字符串中删除标点符号的最佳方法

当尝试从 Python 中的字符串中删除标点符号时,可以使用以下方法:

1

2

3

import string

s = "string. With. Punctuation?"  # Sample string

out = s.translate(string.maketrans("",""), string.punctuation)

登录后复制

但是,这种方法可能显得过于复杂。有没有更简单的解决方案?

效率角度

为了达到最佳效率,很难超越:

1

s.translate(None, string.punctuation)

登录后复制

这段代码利用了C的原始字符串使用查找表进行操作,提供高度优化的

替代方法

如果速度不是主要问题,请考虑以下替代方法:

1

2

exclude = set(string.punctuation)

s = ''.join(ch for ch in s if ch not in exclude)

登录后复制

此选项比使用更快s.replace 每个字符,但仍然优于非纯 Python 方法,例如string.translate.

时序分析

为了比较这些方法的性能,使用以下时序代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

import re, string, timeit

 

s = "string. With. Punctuation"

exclude = set(string.punctuation)

table = string.maketrans("","")

regex = re.compile('[%s]' % re.escape(string.punctuation))

 

def test_set(s):

    return ''.join(ch for ch in s if ch not in exclude)

 

def test_re(s):

    return regex.sub('', s)

 

def test_trans(s):

    return s.translate(table, string.punctuation)

 

def test_repl(s):

    for c in string.punctuation:

        s=s.replace(c,"")

    return s

 

print "sets      :",timeit.Timer('f(s)', 'from __main__ import s,test_set as f').timeit(1000000)

print "regex     :",timeit.Timer('f(s)', 'from __main__ import s,test_re as f').timeit(1000000)

print "translate :",timeit.Timer('f(s)', 'from __main__ import s,test_trans as f').timeit(1000000)

print "replace   :",timeit.Timer('f(s)', 'from __main__ import s,test_repl as f').timeit(1000000)

登录后复制

结果表明:

  • 基于集合的方法比正则表达式或字符串效率低翻译。
  • string.translate 的性能优于 set 和正则表达式方法。
  • replace 方法是最慢的。

因此,为了高效标点符号去除,它是建议使用 s.translate(None, string.punctuation) (对于较低的 Python 版本)或s.translate(str.maketrans('', '', string.punctuation)) (对于更高的 Python 版本)代码。

以上是在 Python 中从字符串中删除标点符号的最有效方法是什么?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板