看起来应该有比这更简单的方法:
import string
s = "string. With. Punctuation?" # Sample string
out = s.translate(string.maketrans("",""), string.punctuation)
有吗?
看起来应该有比这更简单的方法:
import string
s = "string. With. Punctuation?" # Sample string
out = s.translate(string.maketrans("",""), string.punctuation)
有吗?
从效率的角度来看,你不会超越
s.translate(None, string.punctuation)
对于更高版本的Python,请使用以下代码:
s.translate(str.maketrans('', '', string.punctuation))
它在C中使用查找表执行原始字符串操作 - 没有什么比编写自己的C代码更好了。
如果速度不是问题,另一个选择是:
exclude = set(string.punctuation)
s = ''.join(ch for ch in s if ch not in exclude)
这种方法比逐个字符使用s.replace更快,但性能不如正则表达式或string.translate等非纯Python方法,可以从下面的时间对比中看出。 对于这种类型的问题,尽可能地在尽可能低的层次上解决会更好。
时间代码:
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): # From Vinko's solution, with fix.
return regex.sub('', s)
def test_trans(s):
return s.translate(table, string.punctuation)
def test_repl(s): # From S.Lott's solution
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)
这将产生以下结果:
sets : 19.8566138744
regex : 6.86155414581
translate : 2.12455511093
replace : 28.4436721802
table = string.maketrans("","")
替换为table = str.maketrans({key: None for key in string.punctuation})
。新的代码可以去除字符串中的所有标点符号并创建一个映射表,而不是创建一个空的映射表。 - SparkAndShineregex
现在是最高效的方法!它比translate
快近2倍。此外,sets
和replace
也不再效率低下!它们两者都提高了4倍以上 :) - Ryan Soklaski如果你了解正则表达式,那么它们就足够简单。
import re
s = "string. With. Punctuation?"
s = re.sub(r'[^\w\s]','',s)
s = re.sub(r'[^\w\s]','',s, re.UNICODE)
。在Linux上使用Python 3测试时,即使没有使用该标志,也可以使用泰米尔文字母 தமிழ்。 - Matthias为了方便使用,我总结了Python 2和Python 3中从字符串中去除标点符号的注释。详细描述请参考其他答案。
Python 2
import string
s = "string. With. Punctuation?"
table = string.maketrans("","")
new_s = s.translate(table, string.punctuation) # Output: string without punctuation
Python 3
import string
s = "string. With. Punctuation?"
table = str.maketrans(dict.fromkeys(string.punctuation)) # OR {key: None for key in string.punctuation}
new_s = s.translate(table) # Output: string without punctuation
myString.translate(None, string.punctuation)
str
和Python 2中的unicode
中,不支持deletechars
参数。 - agfstring.punctuation
只包含 ASCII 字符!更正确(但也更慢)的方法是使用 unicodedata 模块:
# -*- coding: utf-8 -*-
from unicodedata import category
s = u'String — with - «punctation »...'
s = ''.join(ch for ch in s if category(ch)[0] != 'P')
print 'stripped', s
您可以进行泛化并剥离其他类型的字符:
''.join(ch for ch in s if category(ch)[0] not in 'SP')
根据不同的观点,它还会剥离像~*+§$
这样的字符,这些可能是或可能不是“标点符号”。
~
这样的字符并不属于标点符号类别。您还需要测试符号类别。 - C.J. Jackson并不一定更简单,但如果您更熟悉re系列,这是一种不同的方法。
import re, string
s = "string. With. Punctuation?" # Sample string
out = re.sub('[%s]' % re.escape(string.punctuation), '', s)
我通常使用这样的东西:
>>> s = "string. With. Punctuation?" # Sample string
>>> import string
>>> for c in string.punctuation:
... s= s.replace(c,"")
...
>>> s
'string With Punctuation'
reduce(lambda s,c: s.replace(c, ''), string.punctuation, s)
。 - jfsstr
或Python 2的unicode
值,str.translate()
仅接受字典作为参数;该映射将查找代码点(整数),并删除任何映射到None
的内容。import string
remove_punct_map = dict.fromkeys(map(ord, string.punctuation))
s.translate(remove_punct_map)
dict.fromkeys()
类方法 可以轻松地创建映射字典,将所有的值根据键序列设置为 None
。
要删除所有标点符号,而不仅仅是 ASCII 标点符号,您的表格需要稍微大一些。请参见 J.F. Sebastian 的答案(Python 3 版本):
import unicodedata
import sys
remove_punct_map = dict.fromkeys(i for i in range(sys.maxunicode)
if unicodedata.category(chr(i)).startswith('P'))
unicode
对象和Python 2 str
对象。 - Martijn Pietersstring.punctuation
没有包含现实生活中常用的许多标点符号。那么,有没有一种适用于非ASCII标点符号的解决方案呢?
import regex
s = u"string. With. Some・Really Weird、Non?ASCII。 「(Punctuation)」?"
remove = regex.compile(ur'[\p{C}|\p{M}|\p{P}|\p{S}|\p{Z}]+', regex.UNICODE)
remove.sub(u" ", s).strip()
个人认为这是从Python字符串中删除标点的最佳方法,因为:
$
这样的符号,可以删除\{S}
。\{Pd}
仅会删除破折号。这使用Unicode字符属性,您可以在维基百科上阅读更多信息。
remove = regex.compile(ur'[\p{C}|\p{M}|\p{P}|\p{S}|\p{Z}]+', regex.UNICODE)
。 - John Stud我还没有看到这个答案。只需使用正则表达式;它会删除除单词字符(\w
)和数字字符(\d
)以外的所有字符,后跟一个空格字符(\s
):
import re
s = "string. With. Punctuation?" # Sample string
out = re.sub(ur'[^\w\d\s]+', '', s)
\d
在\w
中已经包含,因此是多余的。 - blhsing\w
的描述:https://docs.python.org/3/library/re.html - blhsing
The temperature in the O'Reilly & Arbuthnot-Smythe server's main rack is 40.5 degrees.
" 包含了一个标点符号,即第二个句点。请注意不要改变原意。 - John Machinstring.punctuation
根本不包括非英文标点符号。我在想的是“。”、“!”, “?”、“:”、“×”、““”、“””、〟等等。 - Clément' '
是标点符号。 - Wayne Werner