>  기사  >  백엔드 개발  >  파이썬에서 구두점을 제거하는 방법

파이썬에서 구두점을 제거하는 방법

尚
원래의
2019-07-01 09:34:4019635검색

파이썬에서 구두점을 제거하는 방법

파이썬에서 문장 부호를 제거하는 방법은 다음과 같습니다.

방법 1:

str.isalnum:

S.isalnum() -> bool

반환 값: 문자열에 하나 이상의 문장 부호가 있는 경우 문자이고 모든 문자는 문자 또는 숫자이면 True를 반환하고, 그렇지 않으면 False를 반환합니다.

예:

>>> string = "Special $#! characters   spaces 888323"
>>> ''.join(e for e in string if e.isalnum())
'Specialcharactersspaces888323'

는 문자와 숫자만 인식할 수 있으며 매우 치명적이며 한자, 공백 등도 죽일 수 있습니다.

방법 2:

string.tempoation

import re, string

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

# 写法一:
out = s.translate(string.maketrans("",""), string.punctuation)

# 写法二:
out = s.translate(None, string.punctuation)

# 写法三:
exclude = set(string.punctuation)
out = ''.join(ch for ch in s if ch not in exclude)

# 写法四:
>>> for c in string.punctuation:
			s = s.replace(c,"")
>>> s
'string With Punctuation'

# 写法五:
out = re.sub('[%s]' % re.escape(string.punctuation), '', s)
## re.escape:对字符串中所有可能被解释为正则运算符的字符进行转义

# 写法六:
# string.punctuation 只包括 ascii 格式; 想要一个包含更广(但是更慢)的方法是使用: unicodedata module :
from unicodedata import category
s = u'String — with - «Punctuation »...'
out = re.sub('[%s]' % re.escape(string.punctuation), '', s)
print 'Stripped', out
# 输出:u'Stripped String \u2014 with  \xabPunctuation \xbb'
out = ''.join(ch for ch in s if category(ch)[0] != 'P')
print 'Stripped', out
# 输出:u'Stripped String  with  Punctuation '


# For Python 3 str or Python 2 unicode values, str.translate() only takes a dictionary; codepoints (integers) are looked up in that mapping and anything mapped to None is removed.
# To remove (some?) punctuation then, use:
import string
remove_punct_map = dict.fromkeys(map(ord, string.punctuation))
s.translate(remove_punct_map)


# Your method doesn't work in Python 3, as the translate method doesn't accept the second argument any more. 
import unicodedata
import sys
tbl = dict.fromkeys(i for i in range(sys.maxunicode) if unicodedata.category(chr(i)).startswith('P'))
def remove_punctuation(text):
	return text.translate(tbl)

방법 3:

re

예:

import re
s ="string. With. Punctuation?"
s = re.sub(r'[^\w\s]','',s)

테스트:

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)

out_put:
# sets : 19.8566138744
# regex : 6.86155414581
# translate : 2.12455511093
# replace : 28.4436721802

더 많은 Python 관련 기술 기사를 보려면 Python Tutorial 칼럼을 방문하여 알아보세요!

위 내용은 파이썬에서 구두점을 제거하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.